如何根据反应功能组件中的先前状态有条件地更新状态?

Cha*_*ika 7 reactjs react-hooks

所以,我想做以下事情,

const [value, setValue] = useState({})
const updateName = (name)
setValue(previousState => {
  if (/*check some conditions*/) {
    // dont update the state
  } else {
    return { /* some new state */ }
  }
});
Run Code Online (Sandbox Code Playgroud)

无论如何我怎样才能实现它?

cbd*_*per 16

你快到了。

const [value, setValue] = useState({})

setValue((prevState) => {
  if (condition to not update) {
    return prevState;
  } else {
    return newState;
  }
});
Run Code Online (Sandbox Code Playgroud)

您不一定需要通过setValue通话来完成此操作。你也可以这样做:

const updateSomething = () => {
  if (shouldUpdate)
    setValue(newState);
}
Run Code Online (Sandbox Code Playgroud)