Javascript 反应 - 状态未更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29490581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React - State not updated
提问by martins
Here I try to set state.autocompleteto 'hello' and then print it, but state seems to be null. How can that be when I just updated the state using setState? datais set as a global variable.
在这里,我尝试设置state.autocomplete为 'hello' 然后打印它,但 state 似乎为 null。当我刚刚使用更新状态时怎么会这样setState?data设置为全局变量。
var data = {
populate_at: ['web_start', 'web_end'],
autocomplete_from: ['customer_name', 'customer_address']
};
var AutocompleteFromCheckboxes = React.createClass({
handleChange: function(e) {
this.setState( { autocomplete_from: 'event.target.value' } );
console.log('autocompleteFrom state: ', this.state.autocomplete_from);
// ^ => Uncaught TypeError: Cannot read property 'autocomplete_from' of null
return 1;
},
render: function() {
var autocompleteFrom = this.props.autocomplete_from.map(function(value) {
return (
<label for={value}>
<input type="checkbox" name={value} value="{value}"
onChange={this.handleChange.bind(this)}
ref="autocomplete-from"/>
{value}
</label>
);
}, this);
return (
<div className="autocomplete-from">
{autocompleteFrom}
</div>
);
}
});
var DynamicForm = React.createClass({
getInitialState: function() {
return {
name : null,
populate_at : null,
same_as : null,
autocomplete_from : "not set",
title : null
};
},
saveAndContinue: function(e) {
e.preventDefault();
var data = {
name : this.refs.name.getDOMNode().value,
};
console.log('data: ' + data.name);
},
render: function() {
return (
<AutocompleteFromCheckboxes
autocomplete_from={this.props.data.autocomplete_from} />
);
}
});
var mountpoint = document.getElementById('dynamic-form');
if ( mountpoint ) {
React.render(<DynamicForm data={data} />, mountpoint);
}
});
回答by Anthony Blackshaw
From the reactjs docs:
来自 reactjs 文档:
setState()does not immediately mutatethis.statebut creates a pending state transition. Accessingthis.stateafter calling this method can potentially return the existing value.
setState()不会立即变异,this.state而是创建一个挂起的状态转换。this.state调用此方法后访问可能会返回现有值。
https://facebook.github.io/react/docs/component-api.html
https://facebook.github.io/react/docs/component-api.html
What you can do is pass a callback function to setStatewhich is triggered once the state has been updated:
您可以做的是传递一个回调函数,setState一旦状态更新就会触发该回调函数:
this.setState(
{autocomplete_from: ...},
function () {
... at this point the state of the component is set ...
}
)
回答by deowk
You need to set the initial state of your component, try adding the following to the top of your component.
您需要设置组件的初始状态,请尝试在组件顶部添加以下内容。
getInitialState: function() {
return {
autocomplete_from: ''
};
}
EDIT:
编辑:
In your DynamicFrom component you have:
在您的 DynamicFrom 组件中,您有:
render: function() {
return (
<AutocompleteFromCheckboxes
autocomplete_from={this.props.data.autocomplete_from} />
);
}
Since you are trying to reference the state you should write
由于您正在尝试引用您应该编写的状态
autocomplete_form={this.state.autocomplete_from}
Also you are trying to set the state from a child component and it should not directly modify state. The best way to approach this is to pass down a function from DynamicFrom(holds the state) to AutocompleteFromCheckboxes. Like so.
此外,您正在尝试从子组件设置状态,并且不应直接修改状态。解决这个问题的最好方法是将一个函数从 DynamicFrom(保持状态)传递给 AutocompleteFromCheckboxes。像这样。
var DynamicForm = React.createClass({
handleChange: function(value) {
this.setState({autocompelete_from: value});
},
render: function() {
return(
<AutocompleteFromCheckboxes
autocomplete_from={this.state.autocomplete_from}
handleChange={this.handleChange}
/>
);
},
....
});
Then call that function in your child component
然后在您的子组件中调用该函数
AutocompleteFromCheckboxes = React.createClass({
....
onChange={this.handleChange}
....
handleChange: function(e) {
this.props.handleChange(e.target.value);
}
});
回答by Hemadri Dasari
To see updated state value after doing setState you should do something like below
要在执行 setState 后查看更新的状态值,您应该执行以下操作
this.setState( { autocomplete_from: 'event.target.value' }, () => {
console.log(this.state.autocomplete_from);//this will print the updated state value
});

