Javascript React类:setState不执行任何操作(并且未报告任何错误)
我有一个使用此构造函数的React类:Javascript React类:setState不执行任何操作(并且未报告任何错误),javascript,reactjs,setstate,Javascript,Reactjs,Setstate,我有一个使用此构造函数的React类: class AddList extends Component { constructor(props){ super(props); this.state = { hidden: true }; } 那么我有这个功能: handleSubmit(e) { e.preventDefault(); // this prevents the page from reloading -- do not delete this line! //
class AddList extends Component {
constructor(props){
super(props);
this.state = { hidden: true };
}
那么我有这个功能:
handleSubmit(e) {
e.preventDefault(); // this prevents the page from reloading -- do not delete this line!
// Implement the rest of this function here!
alert('this.state.hidden: ' + this.state.hidden);
if (this.state.hidden == true){
alert('setting hidden to false');
this.setState({hidden: false});
}
else{
alert('setting hidden to true');
this.setState({hidden: true});
}
alert('this.state.hidden: ' + this.state.hidden);
. . .
My problem is that neither this.setState({hidden: false);
nor this.setState({hidden: 'false');
改变状态!
“警报”框确认通过代码的路径,只有“设置状态”似乎是NOP setState是异步的,因此您以后将无法看到更新。这就是为什么在上次警报调用中看不到最新值的原因 有关更多信息,请查看ReactJs的文档: 我根据您的代码编写了一个示例代码: 类AddList扩展了React.Component{ 构造器{ 超级作物 this.state={hidden:true} this.handleSubmit=this.handleSubmit.bindthis } 把手排气管{ event.preventDefault this.setState{hidden:!this.state.hidden} } 渲染{ 回来 状态值:{this.State.hidden?'hidden':'visible'} 点击我 } } ReactDOM.render,document.getElementById'root' setState是异步的,因此您以后将无法看到更新。这就是为什么在上次警报调用中看不到最新值的原因 有关更多信息,请查看ReactJs的文档: 我根据您的代码编写了一个示例代码: 类AddList扩展了React.Component{ 构造器{ 超级作物 this.state={hidden:true} this.handleSubmit=this.handleSubmit.bindthis } 把手排气管{ event.preventDefault this.setState{hidden:!this.state.hidden} } 渲染{ 回来 状态值:{this.State.hidden?'hidden':'visible'} 点击我 } } ReactDOM.render,document.getElementById'root'
如果要在更新状态值后读取状态值,可以使用setState方法的第二个参数,这是一个回调函数。此回调函数在状态更新和组件重新呈现后执行。例如。
this.setState{hidden:!this.state.hidden},函数{console.logupdated state:+this.state.hidden;} 如果要在更新状态值后读取状态值,可以使用setState方法的第二个参数,这是一个回调函数。此回调函数在状态更新和组件重新呈现后执行。例如。
this.setState{hidden:!this.state.hidden},函数{console.logupdated state:+this.state.hidden;} 只有“设置状态”似乎是否定的!。你是什么意思?我们能看看你想做什么的完整文件吗?这些代码片段不清楚。如果某个东西不起作用,背后会有一个合理的原因,在这种情况下,原因是:setState行为是异步的:只有“setState”似乎是NOP!。你是什么意思?我们能看看你想做什么的完整文件吗?这些代码片段不清楚。如果某些内容不起作用,则背后会有一个有效的原因,在这种情况下,原因是:setState行为是异步的:*correction setState是异步的*correction setState是异步的