父状态不更新子组件

时间:2017-04-22 08:57:27

标签: javascript reactjs

状况:

当我通过单击“开始”启动模拟时,我的“清除”按钮应该会停止它。但是当我点击Clear时,没有任何反应。为什么以及如何解决?

CODE:

Game.jsx

var Game = createReactClass ({

    getInitialState() {
        return {
            start: false
        }
    },

    handleStartClick() {
        this.setState({
            start: true
        })
    },

    handleClearClick() {
        this.setState({
            start: false
        })
    },

    render() {
        return (
            <div>
                <h1>React.js Game of Life</h1>
                <div className="buttons"> 
                    <button className="btn btn-danger" onClick={this.handleClearClick}>Clear</button>
                    <button className="btn btn-success" onClick={this.handleStartClick}>Start</button>
                </div>
                <Board start={this.state.start}/>
            </div>
        );
    }

})

Board.jsx

var Board = createReactClass ({

    getInitialState() {
        var cellArray = [];
        for (var y = 0; y < 40; y++) {
            var cells = [];
            for (var x = 0; x < 40; x++) {
                cells.push(<Cell key={x + y*40} id = {x + y*40} row = {x} column={y} />);
            }
            cellArray.push(cells);
        }
        return {
            array: cellArray
        }
    },

    render() {

        var rows = [];
        for (var y = 0; y < 40; y++) {
            var cells = [];
            for (var x = 0; x < 40; x++) {
                cells.push(<Cell start= {this.props.start} array={this.state.array} key={x + y*40} id = {x + y*40} row = {x} column={y} />);
            }
            rows.push(<tr key={y}>{cells}</tr>);
        }
        return <table><tbody>{rows}</tbody></table>;

    }

})

Cell.jsx

componentWillReceiveProps(nextProps) {

        nextProps.array[nextProps.id] = this;

        var evolution;

        if(nextProps.start && this.state.started == false) {
            evolution = setInterval(() => { 
                this.life(nextProps);
                console.log("DYING:"+this.state.dying);
                this.setState({
                    selected: !this.state.dying
                });
            }, 500);
            this.setState({
                started: true
            })
        } 
        else {
            clearInterval(evolution);
            this.setState({
                started: false
            })
        }
    },

1 个答案:

答案 0 :(得分:1)

您应该将进化间隔保存到状态,以便在新道具进入取消时可以访问它。

&#13;
&#13;
if(nextProps.start && this.state.started == false) {
    let evolution = setInterval(() => { 
        this.life(nextProps);
        console.log("DYING:"+this.state.dying);
        this.setState({
            selected: !this.state.dying
        });
    }, 500);
    this.setState({
        started: true,
        evolution
    })
}
else {
    clearInterval(this.state.evolution);
    this.setState({
        started: false
    })
}
&#13;
&#13;
&#13;