Answer the question
In order to leave comments, you need to log in
Why does a component have to accept a parameter as an object to process an array via map()?
Welcome all.
A meticulous question arose, because I want to understand why it works this way, because it is such a pleasure to learn the axioms in the work of the language by heart.
There is a main component "Main", which contains an array. I pass it to the "Second" component, where I iterate over this array through map and return JSX. I'm passing the array as a normal prop.
As everyone knows, map only works with arrays. It would seem that everything is logical. In the component function, I accept a parameter that will have the array type.<Second array={this.state.array} />
const Second = (array) => {
return (...) // чтобы не раздувать вопрос
}
TypeError: array.map is not a function
const Second = ({array}) => {
return (...)
}
Answer the question
In order to leave comments, you need to log in
Because the component takes all props in 1 single argument - the props object, which already contains your array in the array field
Curly braces are object destructuring, that is, you extract the object field into a variable of the same name, in fact, this is
const Second = ({array}) => {
return (...)
}
similar to this:const Second = (props) => {
const {array} = props;
return (...)
}
which in turn can lead to this:const Second = (props) => {
const array = props.array;
return (...)
}
but with the only difference that in the original example there is no separate props variable
You read the documentation badly, a functional component has an input parameter - props
https://uk.reactjs.org/docs/components-and-props.html
https://learn.javascript.ru/destructuring
Your last entry is similar to this
const Second = (props) => {
const array = props.array;
return (...)
}
const Second = (props) => {
const {array} = props;
return (...)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question