【问题标题】:ReactJS child state not updating after parent state changed父状态更改后ReactJS子状态不更新
【发布时间】:2016-10-02 16:20:34
【问题描述】:

我有一个按钮,当它被按下时,它将更新其父级的状态,这反过来又会更改父级的子元素的文本。

我有一个作为父类的 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>
        );
    }
})

这是我的导航栏类:

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>
        );
    }
})

我做错了什么?

【问题讨论】:

标签: reactjs


【解决方案1】:

修复了问题,只是在子类中对其进行了更改,以便我调用 {this.props.id} 而不是 {this.state.id},并删除了子类中的额外函数(componentDidMount、getInitialState)。

【讨论】:

    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 2021-03-31
    • 2019-05-31
    • 2016-09-18
    • 2021-06-08
    • 2019-07-12
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多