父状态更改后,ReactJS子状态未更新

时间:2016-06-02 19:04:23

标签: reactjs

我有一个按钮,当按下它时,它会更新其父级的状态,然后更改父级的子元素的文本。

我有一个SiteContainer类(用作父类)和一个NavBar类(它是子类)。 NavBar类包含两个元素,一个是按钮,另一个是标签。我想要它,当我按下按钮时,它将调用父进程中的一个函数,它将更新其状态,然后更新子元素的状态

我的问题是,当我点击按钮后更新父状态时,新状态不会传递给孩子重新渲染。

这是我的SiteContainer类:

var SiteContainer = React.createClass({
    getRandomCustomerID: function() {
        console.log("getting random id");
        //just setting a test state for now, to fetch from server later
        this.setState({id: "test"});
    },
    getInitialState: function() {
        return {id: "customer_id"};
    },
    render: function() {
        return (
            <div>
                <NavBar id={this.state.id} getRandomCustomerID={this.getRandomCustomerID}/>
            </div>
        );
    }
})

这是我的NavBar类:

var NavBar = React.createClass({
    componentDidMount: function() {
        this.setState({id: this.props.id});
    },
    onClick: function() {
        console.log("next button pressed");
        this.props.getRandomCustomerID();
    },
    getInitialState: function() {
        return {id: this.props.id};
    },
    render: function() {
        return (
            <div className="row">
                <div className="col-md-6">
                    <h3>Customer ID: {this.state.id}</h3>
                </div>
                <div className="col-md-6">
                    <button className="btn btn-primary" onClick={this.onClick}>Next</button>
                </div>
            </div>
        );
    }
})

我做错了什么?

1 个答案:

答案 0 :(得分:0)

修复了问题,只是在子类中更改了它,以便我调用{this.props.id}而不是{this.state.id},并删除了子节点中的额外函数(componentDidMount,getInitialState)。 / p>