作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
更新 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/
我是一名优秀的程序员,十分优秀!