javascript - 当父组件的状态更新时,子组件的 props 不会更新

标签 javascript reactjs

我正在制作一款四子棋游戏。每列(组件)都会从父组件接收当前玩家颜色作为 Prop 。我在每列中都有一个回调函数,每次单击列时都会更改当前玩家状态,但由于某种原因,列不会接受新的父状态作为更新的 Prop 。

class App extends React.Component {
    constructor() {
        super()

        this.state = {
            currentPlayer: 'red',
            board: null,
        }
    }

    changePlayer = () => {
        this.state.currentPlayer === 'red' ?
            this.setState({
                currentPlayer: 'yellow'
            }) :
            this.setState({
                currentPlayer: 'red'
            })
    }

    componentDidMount() {
        let newBoard = [];
        for(let x = 0; x < 7; x++) {
            newBoard.push(<Column 
                key={`column ${x}`} 
                currentPlayer={this.state.currentPlayer} 
                changePlayer={this.changePlayer}
                x={x} 
            />)
        }

        this.setState({
            board: newBoard,
        })
    }

    render() {
        return(
            <div className="app">
                <div className="board">
                    {this.state.board}
                </div>
            </div>
        )
    }
}
class Column extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            colors: ['white', 'white', 'white', 'white', 'white', 'white']
        }
    }

    handleClick = () => {
        for(let i = 0; i < 6; i++) {
            if(this.state.colors[i] === 'white') {
                let newColors = this.state.colors;
                newColors[i] = this.props.currentPlayer;
                this.setState({
                    colors: newColors
                })
                break;
            }
        }

        this.props.changePlayer();
    }

    render() {
        let column = [];
        for(let y = 5; y >= 0; y--) {
            column.push(<Tile 
                key={`${this.props.x},${y}`} 
                x={this.props.x} 
                y={y} 
                color={this.state.colors[y]}
            />)
        }

        return(
            <div className="column" onClick={() => this.handleClick()}>
                {column}
            </div>
        )
    }
}

我假设问题在于列是使用 componentDidMount 生命周期 Hook 创建的?如果是这种情况,我怎样才能在不改变太多代码结构的情况下解决这个问题?

最佳答案

尚不清楚您的代码在哪里失败,但是:

    // Here you are setting a reference to the array in state, not a copy
    let newColors = this.state.colors;
    // Here you are mutating directly the state (antipattern!)
    newColors[i] = this.props.currentPlayer;
    // You are setting the reference to the array that has already mutated (prevState === nextState)
    this.setState({
     colors: newColors
    });

而是这样做:

    // Make a COPY of your array instead of referencing it
    let newColors = [...this.state.colors];
    // Here you are mutating your CLONED array
    newColors[i] = this.props.currentPlayer;
    // You are setting the NEW color array in the state
    this.setState({
     colors: newColors
    });

好的,我已经解决了您的问题。

App.js 中的更改:

for(let x = 0; x < 7; x++) {
    newBoard.push(<Column 
        key={`column ${x}`}
        // retrieve value with a method as below 
        currentPlayer={() => this.state.currentPlayer} 
        changePlayer={this.changePlayer}
        x={x} 
    />)
}

在 Columns.js 中:

newColors[i] = this.props.currentPlayer();

工作示例:

https://stackblitz.com/edit/react-zzoqzj?file=Column.js

关于javascript - 当父组件的状态更新时,子组件的 props 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60189074/

相关文章:

javascript - 如何在 React 中保持高级用户状态同步?

javascript - 在moment js中将已知时区的时间转换为本地时区

javascript appendChild 不起作用

javascript - 在 Material-ui 按钮上调用 onClick 事件的 Action 创建者不起作用

javascript - 为什么 ReactJS 仅在本地主机上呈现图表中的数据值?

reactjs - 模块解析失败:filename. jsx,您可能需要适当的加载器来处理此文件类型

javascript - 何时使用调用 javascript 函数作为参数及其优点

javascript - AngularJS:服务器端记录客户端错误

javascript - 为什么 isDefaultPrevented 检查 modal.js 中的 div?

javascript - 为什么我的 react-router 链接会把我带到页面中间?