这里我尝试将state.autocomplete
设置为'hello'然后打印它,但状态似乎为空。当我刚刚使用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);
}
});
答案 0 :(得分:112)
来自reactjs docs:
setState()
不会立即改变this.state
,但会创建待处理状态转换。在调用此方法后访问this.state
可能会返回现有值。
https://facebook.github.io/react/docs/component-api.html
您可以做的是将回调函数传递给setState
,该状态在状态更新后触发:
this.setState(
{autocomplete_from: ...},
function () {
... at this point the state of the component is set ...
}
)
答案 1 :(得分:2)
您需要设置组件的初始状态,尝试将以下内容添加到组件的顶部。
getInitialState: function() {
return {
autocomplete_from: ''
};
}
编辑:
在DynamicFrom组件中,您有:
render: function() {
return (
<AutocompleteFromCheckboxes
autocomplete_from={this.props.data.autocomplete_from} />
);
}
因为你试图引用你应该写的状态
autocomplete_form={this.state.autocomplete_from}
此外,您正在尝试从子组件设置状态,而不应直接修改状态。解决此问题的最佳方法是将一个函数从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}
/>
);
},
....
});
AutocompleteFromCheckboxes = React.createClass({
....
onChange={this.handleChange}
....
handleChange: function(e) {
this.props.handleChange(e.target.value);
}
});
答案 2 :(得分:1)
要在执行setState之后查看更新后的状态值,您应该执行以下操作
this.setState( { autocomplete_from: 'event.target.value' }, () => {
console.log(this.state.autocomplete_from);//this will print the updated state value
});