D
D
Dominik092020-01-11 00:48:06
JavaScript
Dominik09, 2020-01-11 00:48:06

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 (...) // чтобы не раздувать вопрос
}

I am getting the following error in the output.
TypeError: array.map is not a function
And I checked which variable I get, and everything is correct: the array type.
I know the solution. It is necessary to circle the parameter in curly brackets.
const Second = ({array}) => {
    return (...)
}

The question is: why should this parameter be enclosed in curly braces? I'm assuming there's some new language standard working here that I don't know about?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2020-01-11
@Dominik09

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

V
Vladimir, 2020-01-11
@Casufi

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 (...)
}

or such
const Second = (props) => {
   const {array} = props;
    return (...)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question