Answer the question
In order to leave comments, you need to log in
How to initialize an empty array and pass it to props?
I am new to ReactJS. I'm building an application that takes JSON data from a file and stores it in the public folder.
class App extends React.Component {
componentDidMount() {
axios.get('http://localhost:3000/pizza.json').then(data => {
store.dispatch(setPizza(data.Pizza))
})
}
<Route path="/" render = { () => <Main items={ this.props.items }/>} exact></Route>
function Item({ image, name, types, sizes, price }) {
const availableTypes = ['0', '1'];
const availableSizes = [26, 30, 40];
const [activeType, setActiveType] = useState(types[0])
const [activeSize, setActiveSize] = useState(sizes[0])
const onSelectType = index => {
setActiveType(index)
}
const onSelectSize = index => {
setActiveSize(index)
}
return (
<div className="item">
<img src={ image } alt="pizza1" className="item-preview"/>
<h3 className="item-name">{ name }</h3>
<div className="item-dimantion">
<ul className="list">
{
availableTypes.map((type, index) => (
<li
key={type}
className={classNames({
choice: true,
active: activeType === index ? 'active' : '',
disable: types.includes(index)
})}
onClick={() => onSelectType(index)}>
{ type }
</li>
))}
</ul>
<ul className="list">
{
availableSizes.map((size, index) => (
<li key={ size }
className={classNames({
choice: true,
active: activeSize === index ? 'active' : '',
disable: sizes.includes(index)
})}
onClick={() => onSelectSize(index)}>
{ size } см.
</li>
))
}
</ul>
</div>
<div className="more">
<h4 className="price">от { price }</h4>
<button className="add">Добавить</button>
</div>
</div>
)
}
function Main({ items }) {
...
<div className="main__content__items">
{
items.map(obj => {
return (
<Item key={obj}></Item>
)
})
}
</div>
console.log(Array.isArray(this.props.items))
Answer the question
In order to leave comments, you need to log in
componentDidMount is called after the component and all of its children are mounted (hence when we try to use props.items the json request hasn't even been sent yet).
We can assign an empty array for items in initialState to get rid of this error, or we can add an auxiliary state that would check if we have data loaded, and if so, display it.
Why can't you just call this request in componentDidMount on the Main page? What kind of perversion is it to call it in the App and pass it as a prop to the route?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question