为什么状态在redux开发工具中进行了更新,但在实时状态下未进行更新

时间:2019-09-13 14:18:34

标签: reactjs redux state action reducers

当用户提交按钮时,我为登录创建模式,为发送电子邮件以及通过和历史发送调度auth,并且在响应正常之后,应该调度idToken和isAuthenticated,在reducer中应该将isAuthenticated更新为true并存储idToken,但是当我使用时在我的组件中,我只看到默认状态,但是在redxu devtools中,我看到了更新状态

action.js

      .then((response) => {
        if (response.status == 200) {
          history.push("/dashboard");
          return dispatch({
            type: AUTH_SUCCESS,
            payload: {
              idToken: response.data.idToken,
              isAuthenticated: true
            }
          });
        }
      })
      .catch((error) => {
        console.log(error.response.data.error.message);
        // dispatch(authFail(error.response.data.error));
      });

reducer.js

export default (state = initialState, action) => {
  switch (action.type) {
    case AUTH_SUCCESS: {
      return {
        ...state,
        idToken: action.payload.idToken,
        isAuthenticated: traction.payload.isAuthenticated
      };
    }

    case AUTH_FAIL:
      return {
        ...state,
        errorCode: action.code,
        errorMessage: action.message
      };

    default:
      return state;
  }
};

privateRoute.js


const PrivateRoute = ({ component: Component, ...rest }) => {

  const authenticated = useSelector((state) =>console.log('state',state.auth));

///state not updated ????

  return (
    <Route
      {...rest}
      render={(props) =>
        authenticated ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
};
export default PrivateRoute;

store.js


import { compose, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";

import rootReducer from "../services/reducer";

export default (initialState) => {
  // initialState = JSON.parse(window.localStorage.getItem('state')) || initialState;

  const middleware = [thunk];
  let enhancer;

  enhancer = compose(
    applyMiddleware(...middleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  );

  const store = createStore(rootReducer, initialState, enhancer);
  // store.subscribe(() => {
  //   const state = store.getState();
  //   const token = {
  //     token: state.auth
  //   };
  //   window.localStorage.setItem("token", JSON.stringify(token));
  // });
  return store;
};

combinereducer.js

import { combineReducers } from 'redux';
import authReducer from './auth/reducer';

export default combineReducers({
    auth:authReducer
})

app


const Root = ({ children, initialState = {} }) => (
  <Provider store={store(initialState)}>{children}</Provider>
);

应用程序中的状态不会更新,但在redux devtools中显示我的状态已更新

0 个答案:

没有答案