【发布时间】:2019-05-16 02:34:50
【问题描述】:
我已经声明了一个名为 account_type 的状态。我创建了一个 onChange 事件,它在单击 div 时更改状态的值。
<div
className="price-plan"
value="star"
onClick={() => this.setPlan("star")}
>
问题是我第一次单击 div 时 account_type 状态没有更新。只有当我单击它两次时它才会更新。有没有办法通过单击 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>
);
}
}
【问题讨论】:
-
setState是异步的,所以当你console.log它时它不会在下一行改变
标签: javascript reactjs events onchange