父组件状态更新时,子组件的道具不更新

时间:2020-02-12 13:06:30

标签: javascript reactjs

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

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生命周期钩子创建了列?在这种情况下,如何在不更改太多代码结构的情况下解决该问题?

1 个答案:

答案 0 :(得分:1)

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

    // 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