Javascript 第一次单击更改时输入状态未绑定
我已经声明了一个名为account\u type的状态。我创建了一个onChange事件,它在单击div时更改状态的值Javascript 第一次单击更改时输入状态未绑定,javascript,reactjs,events,onchange,Javascript,Reactjs,Events,Onchange,我已经声明了一个名为account\u type的状态。我创建了一个onChange事件,它在单击div时更改状态的值 <div className="price-plan" value="star" onClick={() => this.setPlan("star")} > this.setPlan(“star”)} > 问题是,帐户类型状态在我第一次单击div时没有得到更新。它只在我单击它两次
<div
className="price-plan"
value="star"
onClick={() => this.setPlan("star")}
>
this.setPlan(“star”)}
>
问题是,帐户类型状态在我第一次单击div时没有得到更新。它只在我单击它两次时得到更新。有没有一种方法可以通过单击div来更新状态。下面是我的代码摘录,显示了我正在尝试做的事情
let isRedirect = false;
class PricePlan extends React.Component {
constructor(props) {
super(props);
this.state = {
account_type: "",
renderRedirect: false
};
this.handleChange = this.handleChange.bind(this);
}
// Handle fields change
handleChange = input => e => {
this.setState({ [input]: e.target.value });
};
setPlan(plan) {
this.setState({
account_type: plan
});
console.log(this.state.account_type);
// if (this.state.account_type !== undefined) {
// isRedirect = true;
// }
}
render() {
if (isRedirect) {
return (
<Redirect
to={{
pathname: "/sign-up",
state: { step: 2, account_type: this.state.account_type }
}}
/>
);
}
return (
<div
className="price-plan"
value="star"
onClick={() => this.setPlan("star")}
>
<h3>{this.props.planName}</h3>
<div className="mute price-row">Name</div>
<p className="price">Price</p>
<span className="billed-frequency">Cycle</span>
</div>
);
}
}
让isRedirect=false;
类PricePlan扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
帐户类型:“”,
RenderDirect:错误
};
this.handleChange=this.handleChange.bind(this);
}
//处理字段更改
handleChange=input=>e=>{
this.setState({[input]:e.target.value});
};
集合计划(计划){
这是我的国家({
账户类型:计划
});
console.log(this.state.account\u类型);
//if(this.state.account_type!==未定义){
//isRedirect=true;
// }
}
render(){
if(isRedirect){
返回(
);
}
返回(
this.setPlan(“star”)}
>
{this.props.planName}
名称
价格
周期
);
}
}
正如@Jayce444所建议的那样,设置状态
不会立即更新状态
。所以setPlan
应该是
setPlan(plan) {
this.setState({
account_type: plan
});
console.log(plan); // Don't expect immediate state change in event handler
}
但是您可以在render()函数中的任何位置使用this.state.account\u type
。而呈现将在第一次单击时更新此.state.account_type
之后发生。setState
是异步的,因此当您console.log
它时,它不会在下一行被更改