gpt4 book ai didi

javascript - 如何在我的示例中正确使用 setState() ?

转载 作者:行者123 更新时间:2023-12-01 00:46:09 24 4
gpt4 key购买 nike

更新 this.state.processDuration 以避免出现警告消息的正确方法是什么?:

Do not mutate state directly. Use setState() react/no-direct-mutation-state

  fetchData = () => {
this.setState(
this.state.processDuration = (new Date(this.state.endTime)-new Date(this.state.endDate)) / 60000
)
}

最佳答案

setState 接收带有您要更新的键/值的对象作为参数。

您可以查看setState() docs了解更多示例。

像这样使用它:

   fetchData = () => {
this.setState({
processDuration: (new Date(this.state.endTime)-new Date(this.state.endDate)) / 60000
})
}

由于设置状态是异步并且您使用当前状态,因此建议您使用更新器函数而不是传递对象。

   fetchData = () => {
this.setState((state) => ({
processDuration: (new Date(state.endTime)-new Date(state.endDate)) / 60000
}));
}

如果您想在状态更改后执行某些操作,您可以传递一个可选回调,该回调将在状态更新和组件重新渲染后调用:

      this.setState(
// Updater function, has current state/props as parameters
(state, props) => ({
processDuration: (new Date(state.endTime)-new Date(state.endDate)) / 60000
}),
// V -- This will be called after state was updated
() => { console.log('State was updated!', this.state); }
)

关于javascript - 如何在我的示例中正确使用 setState() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57348011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com