this.map[col1][row1] = <MemoizedItem key={item} x={row1} y={col1} /> this.setState({ map: this.map })
This is my code, I’m put all the item in param map. and render by using:
renderItem() { return this.state.map.map((row) => { return row.map((item) => { return item; }) }) }
Now, i’m trying to pass the props color in the item by this.state.map[0][0].props.color ='#fff'
but not working, get an error ‘Cannot add property color, object is not extensible’, so is there any way to do that?
Advertisement
Answer
you should not store components in component state You can just store the data in state like
let data = [{id:'row1', cols:[{id:'col1'}, {id:'col2'}]} , {...}, ...] this.setState({ map: data })
and render it using your memoized component
renderItem() { return this.state.map.map((row, rowIndex) => { return row.cols.map((item,index) => { //you can pass whatever you want to pass to the component return <MemoizedComponent key={rowIndex+index} x={item} y={row} yourprops={condition ? color1: color2} /> }) }) }
finally you can update data by setting state like
let final = this.state.data.map(r => { if (r === 'your condition') { return Object.assign({}, r, { cols: r.cols.map(c => { if (c === 'your col condition') { return Object.assign({}, c, { changedProp: 'changedPropvalue', }); } else { return c; } }), }); }else{ return r } }); ... this.setState({data:final})
so when the state updates the component rerendered
also make sure you use PureComponent as it will restrict rerenders to only changed items