Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应还原器,状态未立即更新_Reactjs_Redux Reducers - Fatal编程技术网

Reactjs 反应还原器,状态未立即更新

Reactjs 反应还原器,状态未立即更新,reactjs,redux-reducers,Reactjs,Redux Reducers,我正在使用createContext和reducers,使用reducers我正在更新状态值,但它不是一次更新值,我使用了console.log(user)在onSubmitSave()中,但在控制台日志中,我一次都没有得到它的更新状态,当我再次单击signin时,我可以看到它工作,这里我已附加了我的全部代码,有人可以查看它,并帮助我解决此问题吗 auth.js import { createContext } from 'react'; const AuthContext = cre

我正在使用
createContext
reducers
,使用reducers我正在更新状态值,但它不是一次更新值,我使用了
console.log(user)
onSubmitSave()
中,但在控制台日志中,我一次都没有得到它的更新状态,当我再次单击signin时,我可以看到它工作,这里我已附加了我的全部代码,有人可以查看它,并帮助我解决此问题吗

auth.js

import { createContext } from 'react';

    const AuthContext = createContext({
      user: null,
      hasLoginError: false,
      login: () => null,
      logout: () => null
    });
    
    export default AuthContext;
签名

// Login button Click
  async function onSubmitSave(e) {
    e.preventDefault();

    const messages = {
      'itemUsername.required': 'Username cannot be empty.',
      'itemPassword.required': 'Password cannot be empty.',
    };
    const rules = {
      itemUsername: 'required',
      itemPassword: 'required|string',

    };
    validateAll(state, rules, messages)
      .then(async () => {
        let data = await login(itemUsername, itemPassword);
        console.log(data);
        console.log("sdsds");
        console.log(user);
        setUserData(user);
      })
      .catch(errors => {
        const formattedErrors = {

        };

        errors.forEach(error => formattedErrors[error.field] = error.message);

        setState({
          ...state,
          errors: formattedErrors
        });
      })

  }
  // End Login 
App.js

const reducer = (state, action) => {

  switch (action.type) {
    case "login": {
      const { username, password } = action.payload;

      return {
        ...state,
        hasLoginError: false,
        user: {
          id: 1,
          username: USERNAME,
          firstName: "Dev",
          lastName: "To"
        }
      };


    }
    case "logout":
      return {
        ...state,
        user: null
      };
    default:
      throw new Error(`Invalid action type: ${action.type}`);
  }
};

您还可以添加
setUserData
方法吗?但它只在登录时起作用。您在App.js中定义这个USERNAME变量的地方?是的,现在我已经在其中传递了静态值。您可以尝试删除
async
wait
并返回
登录(itemUsername,itemPassword)从第一个
块。您可以将另一个
然后
语句与
数据
作为参数进行链接,您可以尝试在其中记录数据并设置用户。