簡體   English   中英

如何在反應中更新深層嵌套狀態?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM