What is the correct way to update this.state.processDuration
in order to avoid a warning message?:
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
receives as argument an Object with the key/values you want to update.
You can look through the setState() docs for more examples.
Use it like this:
fetchData = () => {
this.setState({
processDuration: (new Date(this.state.endTime)-new Date(this.state.endDate)) / 60000
})
}
Because setting state is asynchronous
and you use current state, it is recommended that you use the updater function instead of passing an Object.
fetchData = () => {
this.setState((state) => ({
processDuration: (new Date(state.endTime)-new Date(state.endDate)) / 60000
}));
}
If you want to do something after state was changed, you can pass an optional callback that will be called after state was updated and component re-rendered:
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); }
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.