mar*_*ins 43 javascript reactjs
在这里我尝试设置state.autocomplete为'hello'然后打印它,但状态似乎是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);
}
});
Run Code Online (Sandbox Code Playgroud)
Ant*_*haw 114
来自reactjs文档:
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 ...
}
)
Run Code Online (Sandbox Code Playgroud)