React - State not updated(React - 状态未更新)
问题描述
在这里我尝试将 state.autocomplete
设置为 'hello' 然后打印它,但 state 似乎为空.当我刚刚使用 setState
更新状态时,怎么会这样?data
设置为全局变量.
Here I try to set state.autocomplete
to 'hello' and then print it, but state seems to be null. How can that be when I just updated the state using setState
? data
is set as a global variable.
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);
}
});
推荐答案
来自 reactjs 文档:
From the reactjs docs:
setState()
不会立即改变 this.state
而是创建一个挂起的状态转换.调用此方法后访问 this.state
可能会返回现有值.
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value.
https://facebook.github.io/react/docs/component-api.html
您可以做的是向 setState
传递一个回调函数,该函数在状态更新后触发:
What you can do is pass a callback function to setState
which is triggered once the state has been updated:
this.setState(
{autocomplete_from: ...},
function () {
... at this point the state of the component is set ...
}
)
这篇关于React - 状态未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:React - 状态未更新
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01