componentWillReceiveProps中的setState不更新状态

时间:2018-06-10 00:18:18

标签: javascript reactjs

我正在尝试更新props componentWillReceiveProps的状态 - 但是当我稍后检查值时,它并不反映实际状态变量的更新。因此,UI和状态中的值不同步。 我还尝试将一个与setState相关联的回调函数显示正确的值 - 但在实际应用中,状态仍未更新。

代码段

 this.render = function () {
    var self = this;

     class SearchApp extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                value: [],
                action: "add"
            };
            this.handleClick = this.handleClick.bind(this);
            self.searchInstance = this;
        }

        handleClick(e, value) {
            console.log(value);
        }

        render() {
            return (
                <Search
                    id="readonly_modifyStates"
                    readOnly={true}
                    value={readOnlyTokens}
                    logicMenu={['OR']}
                    action={this.state.action}
                />
            );
        }
};
this.addReadOnlyTokens = function (tokens) {
    // tokens = ['Managed Status = InSync, OutSync']
    readOnlyTokens = tokens;
   // 1 - Sending some value that needs to be updated in the existing 'value' variable
    this.searchInstance.setState({value: tokens, action:"add"});          
};

搜索组件代码

class Search extends React.Component {
componentWillReceiveProps(nextProps) {  
   switch(nextProps.action){
        case "add":
            //2 - The value will be updated on UI using lib addTokens method 
            this.searchWidget.addTokens(nextProps.value);
            break;
    }

    //3- At this moment I need to update the state 'value' so that both the UI and the actual state data is in sync - but not working
    this.setState({value: this.searchWidget.getAllTokens()}, function () {
            // Here, when value is checked - it shows the updated data - But when the control is in Search App code, the value falls back to ['Managed Status = InSync, OutSync'] 
            console.log('this.state ::: ' + JSON.stringify(this.state));
        });
}
render() {
    return (
        <div className="search-component"
             ref={el => this.el = el}>
            {this.props.children}
        </div>
    );
}

我想要做的就是使用状态将值从searchApp发送到组件(用按摩值更新UI)然后能够将这些按摩值同步回应用程序的状态 - 现在是指向setState调用期间使用的数据。

阅读一些文章,似乎在componentWillReceiveProps()中执行setState是可行的 - 但我不确定为什么这些值没有同步。

感谢您的任何指示。

0 个答案:

没有答案