【问题标题】:Transferring state between two components在两个组件之间传输状态
【发布时间】:2015-01-22 16:48:57
【问题描述】:

我有一个用于呈现 searchResult 组件的 searchForm 组件。当 searchForm 获得结果时,它应该将状态传递给结果的状态。 这是我失败的地方。

var SearchForm = React.createClass({
    getInitialState: function () {
        return {
            golden_record: {}
        }
    },
    handleSearchSubmit: function (search_param) {
        $.ajax({
            url: this.props.url_variation,
            type: 'GET',
            data: search_param,
            success: function (data) {
                this.setState(
                    {
                        ...
                    }
                );
            }.bind(this),
        });
        $.ajax({
            url: this.props.url_golden,
            type: 'GET',
            data: search_param,
            success: function (data) {
                var golden_record = {
                    'site': data.sites[0].name,
                    'country': data.sites[0].country,
                };
                this.setState({'golden_record': golden_record});
            }.bind(this),
        })
    },
    render: function () {
        return (

                <div className="searchResult">
                    <SearchResult
                        golden_record={this.state.golden_record}
                    />
                </div>

        );
    }
});

搜索结果:

如您所见,我将 golden_record 作为属性传递给 SearchResult。在 SearchResult 中,当我将 &lt;input /&gt;value 设置为属性 this.props.golden_record['site'] 时,输入固定为该值。但我想将值设置为this.state.site,以便以后可以根据需要更改它。所以我不知道如何将prop的只读值复制到状态。

 <input type="text" className="form-control" placeholder="Facility name" name="facilityName" onChange={this.onSiteChanged} value={this.props.golden_record['site']} ref="facilityName"></input>

有什么建议吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    在您的SearchResult 组件中,您可以在componentWillReceiveProps 中设置您的状态:

    var SearchResult = React.createClass({
      ...
      getInitialState: function(){
         return {
            site: ''
         } 
      },
      componentDidMount: function(){
         this.setState({ site: this.props.golden_record.site });
      },
      componentWillReceiveProps: function(newProps){
         this.setState({ site: newProps.golden_record.site });
      },
      render: function(){
         return  <input type="text" className="form-control" placeholder="Facility name" name="facilityName" onChange={this.onSiteChanged} value={this.state.site} ref="facilityName"></input>
      }
    });
    

    【讨论】:

    • 那行得通。非常感谢。但这里似乎不需要componentDidMount 。解决方案是componentWillReceiveProps
    • 太棒了,很高兴它有效。我只是将componentDidMount 放在那里,因为componentWillReceiveProps 仅在初始安装后调用,我认为您的组件可能会使用数据进行初始化。