[英]How to update deeply nested state in react?
我正在创建一个数独板,它在这样的网格中呈现 JSX div 对象。
newBoard.push(<div className={letnum} key={letcol} id={letcol}
onClick={() => this.handleTileClick(event)}>
{response.data[i][j]}
</div>
然后将 newBoard 添加到状态,但是当我单击一个磁贴将 innerHTML 更改为新数字时,我还想同时更新状态。 我收到错误:
Cannot assign to read only property 'children' of object '#<Object>'
我需要更新:
this.state.board[index].props.children
成为一个新号码。 关于如何做到这一点的任何建议? 我已经做了几个小时了哈哈。 这是总代码。
axios.get("http://127.0.0.1:5000/new-board")
.then(response => {
console.log("API Response: ", response)
for (let i = 0; i < 9; i++) {
let letter = String.fromCharCode(97 + i)
for (let j = 0; j < 9; j++) {
let column = j + 1;
let number = dictionary[j + 1];
let letnum = letter + " " + number + " tile";
let letcol = letter + column;
newBoard.push(<div
className={letnum}
key={letcol}
id={letcol}
onClick={() => this.handleTileClick(event)}>
{response.data[i][j]}
</div>)
}
}
this.setState({
board: newBoard,
winningBoard: newBoard,
gameWon: false
})
})
handleNumberChoiceClick(event) {
this.setState({
activeNumberSelector: Number(event.target.innerHTML)
})
}
handleTileClick(event) {
const selectedTile = event.target;
selectedTile.innerHTML = this.state.activeNumberSelector;
const location = this.state.board.indexOf((this.state.board.find(tile=>tile.props.id === selectedTile.id)));
this.setState({
activeNumberSelector: ''
})
console.log(this.state.board[location].props.children)
}
简单地说:您不应该将 React 元素置于 state 中。
只保留在 state(和 props)中渲染这些元素所需的数据,并在渲染函数中返回这些元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.