简体   繁体   English

React useState setter 不适用于 boolean 值

[英]React useState setter is not working on a boolean value

I tried updating a state value using its setter from the useState hook, but it wouldn't update.我尝试使用useState挂钩中的设置器更新 state 值,但它不会更新。 The same setter is working in a different function while setting the value true.相同的设置器在不同的 function 中工作,同时将值设置为 true。

To make sure that the function call was proper, I tried updating a different state from the the faultering function and it works!为了确保 function 调用正确,我尝试从错误的 function 更新不同的 state 并且它有效!

I have been whacking my head as to why that particular state is not updating to a boolean false value.我一直在思考为什么那个特定的 state 没有更新为 boolean 错误值。

const initialFormState = {
  0: { a: null, b: 0.0, c: 0.0 }
};
const [form, setForm] = useState(initialFormState);
const [fileUploadModal, setFileUploadModal] = useState(false);

function openFileInput() {
  setFileUploadModal(true);  // this works fine
}

function closeFileInput() {
  setFileUploadModal(false);   // this doesn't update
  setForm(initialFormState);   // this works fine as well
  console.log(fileUploadModal, form);
}

To sanity check:进行完整性检查:

useEffect(() => {
  console.log('File open state modified', fileUploadModal);
}, [fileUploadModal]);

This is not updated proving that there is some issue with the state setter.这没有更新,证明 state 设置器存在一些问题。

Sounds like setstate-doesnt-update-the-state-immediately .听起来像setstate-doesnt-update-the-state-immediately Setter is working correct, you must know that setFileUploadModal is asyncronous, you can check updated state in useEffect . Setter 工作正常,您必须知道setFileUploadModal是异步的,您可以在 useEffect 中检查更新的useEffect Example:例子:

const initialFormState = {
    0: { a: null, b: 0.0, c: 0.0 }
  };
  const [form, setForm] = useState(initialFormState);
  const [fileUploadModal, setFileUploadModal] = useState(false);

 function openFileInput() {
    setFileUploadModal(true); 
  }

  function closeFileInput() {
    setFileUploadModal(false);
    setForm(initialFormState);
  }

useEffect(() => {
   console.log(fileUploadModal);
}, [fileUploadModal])

So sorry for the question, but the problem was due to a template issue, the click also triggered the function which sets the value to true.很抱歉这个问题,但问题是由于模板问题,点击也触发了 function 将值设置为 true。 The confusion arose because the state update useEffect was not called, and that lead me to different line of investigation.出现混淆是因为没有调用 state 更新 useEffect,这导致我进行了不同的调查。 The real issue was the btn click was not propagated properly.真正的问题是 btn 点击没有正确传播。

Thanks for the help everyone!感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM