简体   繁体   English

为什么 React Hooks 不更新数据

[英]Why React Hooks doesn't update the data

I try to update the values in the useState with the fetched data.我尝试使用获取的数据更新useState 中的值。 when I console .log data.success it returns true .当我控制台.log data.success它返回true Then I assign it to the success value.然后我将它分配给成功值。 but it returns false !但它返回false why?为什么? why value success doesn't get updated immediately.为什么值成功不会立即更新。 At the end i receive the message from the server that the login was successful.最后我从服务器收到登录成功的消息。 SIGN IN success: false the user admin is logged登录成功:false 用户管理员已登录

const Signin = () => {
  const [values, setValues] = useState({
    success: false
  });

  const { success } = values;

  const clickSubmit = async event => {
    event.preventDefault();

    const signReact = catchAsync(async (email, password) => {
      const data = await signin(email, password) // fetch data from the server
      console.log(data.success); // -> true
      if (data) {
        setValues({
          ...values, success: data.success // -> assign to success
        });
        console.log("SIGN IN success: " + success); // -> false! why?!
      }
      return data;
    });

    signReact(email, password);
  };

setState() is an asynchronus function. setState()是一个异步函数。 So you cannot print it in the next statement.It will take some time.To see the updated state values you can log it in useEffect() like this所以你不能在下一个语句中打印它。这需要一些时间。要查看更新的状态值,你可以像这样在useEffect()记录它

useEffect(()=>{

console.log(values);
},[values])

According to the docs:根据文档:

Calls to setState are asynchronous - don't rely on this.state to reflect the new value immediately after calling setState.对 setState 的调用是异步的 - 不要依赖 this.state 在调用 setState 后立即反映新值。 Pass an updater function instead of an object if you need to compute values based on the current state:如果需要根据当前状态计算值,请传递更新程序函数而不是对象:

Example:例子:

const Signin = () => {
  const [values, setValues] = useState({
    success: false
  });

  const { success } = values;

  React.useEffect(()=> {
    console.log("SIGN IN success: " + success);
  }, [values]);

  const clickSubmit = async event => {
    event.preventDefault();

    const signReact = catchAsync(async (email, password) => {
      const data = await signin(email, password) // fetch data from the server
      console.log(data.success); // -> true
      if (data) {
        setValues({
          ...values, success: data.success // -> assign to success
        });
      }
      return data;
    });

    signReact(email, password);
  };

use useEffect .使用useEffect Try something like this:尝试这样的事情:

useEffect(() => {
    console.log("SIGN IN success: " + values.success);
  }, [values]);

...
...
 const data = await signin(email, password);
 setValues(prevState =>{...prevState, success: data.success});

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

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