反应减速器,状态不立即更新

时间:2020-08-15 09:27:53

标签: reactjs redux-reducers

我正在createContextreducers上工作,用减速器我正在更新状态值,但不是一次更新值,我在console.log(user);中做了onSubmitSave() ,但在控制台日志中,我一次无法获得其更新状态,当我再次单击登录时,我可以看到它的工作状态,这里我已附加了完整的代码,任何人都可以调查一下,并帮助我解决此问题?

auth.js

import { createContext } from 'react';

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

signin.js

// 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}`);
  }
};

0 个答案:

没有答案