在下一个js派发后Redux状态不会改变

时间:2018-09-19 22:20:18

标签: redux redux-thunk next.js

我是下一个js的新手,我使用redux-next-wrapper!

问题是我想调度令牌访问,但是当我在getInitialProps中进行令牌访问时,页面呈现后商店不会更新!

我尝试使用componentDidMount,它可以工作,但是状态仅在页面呈现后才更新,这使按钮登录一秒钟可见,然后才能被注销替换!

  componentDidMount () {
    const token_access = Cookies.get('xxxxxxxxxx');
    const token_refresh = Cookies.get('xxxxxxxxxx');
    console.log(token_access);
    if (token_access && token_refresh) {
      const decode = jwt_decode(token_refresh);
      if (decode.exp >= new Date()) {
        this.props.store.dispatch(logout(token_refresh))
      }
      else {
        const decode_access = jwt_decode(token_access);
        if (decode_access.exp >= new Date()) {
          refresh(token_refresh)
        }
        this.props.store.dispatch(userLoggedIn(token_access));
      }
    }
  }

  static async getInitialProps ({Component, ctx}) {
    const token = '12345';
    ctx.store.dispatch(userLoggedIn(token));
    return {
      pageProps: (Component.getInitialProps ? await Component.getInitialProps(ctx) : {})
    }
  }

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from '../reducers/index'

export default initialState => createStore(
  rootReducer,
  composeWithDevTools(
    applyMiddleware(thunk)
  )
);

有没有一种方法可以在页面呈现之前分派和加载商店?

谢谢您的回答

1 个答案:

答案 0 :(得分:0)

我通过更改商店来解决此问题!希望这可以帮助某人:)

export const initStore = (initialState = {} ) => {
  return createStore(rootReducer,
    initialState, composeWithDevTools(applyMiddleware(thunk)))
};