父组件的状态更新时,子组件的 props 没有更新

3

我正在制作一个连接四子游戏。每一列(组件)从父组件获得当前玩家的颜色作为属性。我在每个列中有一个回调函数,每次点击列时更改当前玩家状态,但由于某种原因,这些列不接受新的父状态作为更新后的属性。

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个回答

3

不清楚您的代码在哪里出现问题,但是:



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


我明白你的意思,那绝对是正确的。谢谢。不幸的是,那似乎并没有解决这个问题。 - Blueprint
你能否在类似 StackBlitz 的平台上重现这段代码片段? - Mosè Raguzzini
你是指像这样的东西吗? https://stackblitz.com/edit/react-sc6ozv - Blueprint
1
这是因为在App.js中,您在render函数之外评估了呈现的组件。因此,props永远不会发生变化。您可以像我所做的那样进行修复(通过方法检索props),或者将组件渲染移到render方法内部,这样它将在每次状态更改时重新评估。 - Mosè Raguzzini
1
问题很简单:props和state在每次渲染时都会被评估,但是在您的代码中,您正在将原始值分配为字符串(因此复制而不是引用)在渲染之外的方法中,并且该值在每次渲染时保持不变,因为它只被评估一次。使用像我的示例中的getter将检查当前状态以返回适当的值。这与React相关性不大,更多地涉及到Javascript。 - Mosè Raguzzini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接