Javascript 声明在第二次提交表单之前不会更新
因此,当添加会话并提交表单时,我希望将客户端的价格转移到会话状态。。这就是我在这部分代码中要做的Javascript 声明在第二次提交表单之前不会更新,javascript,reactjs,redux,state,Javascript,Reactjs,Redux,State,因此,当添加会话并提交表单时,我希望将客户端的价格转移到会话状态。。这就是我在这部分代码中要做的 state = { id: null, name: null, duration: null, dayOfWeek: null, price: null } handleSubmit = (e) => { e.preventDefault(); let newPrice = 0; this.props.clientLi
state = {
id: null,
name: null,
duration: null,
dayOfWeek: null,
price: null
}
handleSubmit = (e) => {
e.preventDefault();
let newPrice = 0;
this.props.clientList.filter(client => {
if (client.name === this.state.name)
{newPrice = client.price}
this.setState({
price : newPrice
});
console.log("price = " + this.state.price, 'newPrice = ' + newPrice)
})
this.props.addSession(this.state);
e.target.reset();
this.setState({
id: null,
name: null,
duration: null,
dayOfWeek : null
});
}
正在发生的事情,我试图在控制台和我添加的两个会话的图像中描述,当我添加它时,它第一次注销时,price=null,newPrice=40,第二次注销时,price=40。为什么我的代码在这里不起作用
如果需要,我可以添加更多代码。让我知道你需要看什么,谢谢 该状态不会立即更新。如果在状态更新后需要回调,可以使用
this.setState({
price : newPrice
}, ()=>{
//CallBack here
console.log("price = " + this.state.price, 'newPrice = ' + newPrice)
})
希望能有帮助。如果我不明白你的问题。请回复设置状态是一个异步函数。。。通过在setState之后直接调用以下行来访问旧状态值:
-
我还刚刚意识到,在代码的最后一部分,我将状态设置回null,我没有price:null。当我添加它时,它甚至不会像以前那样第二次工作。有没有办法让状态及时更新,这样当我提交表单时,数据就可以输出了?我想我不一定需要回调。我只需要它能够发送数据到我的行动的创造者time@josephT设置状态相当快。用户不会看到状态变化之间的差异,可以使用回调。当您提交表单时,数据将根据需要输出。@josephT,如果您需要将newPrice发送给您的操作。您只能将newPrice值发送给动作创建者。由于setState是异步的,因此状态不会立即更新。
this.props.addSession(this.state);
handleSubmit = (e) => {
e.preventDefault();
let newPrice = 0;
this.props.clientList.filter((client) => {
if (client.name === this.state.name) {
newPrice = client.price;
}
this.setState({
price: newPrice,
});
console.log(`price = ${this.state.price}`, `newPrice = ${newPrice}`);
});
this.props.addSession({ ...this.state, price: newPrice }); // <- Look at this
e.target.reset();
this.setState({
id: null,
name: null,
duration: null,
dayOfWeek: null,
});
};