React/Redux - 在应用程序加载/初始化时调度操作

新手上路,请多包涵

我有来自服务器的令牌身份验证,所以当我的 Redux 应用程序最初加载时,我需要向该服务器发出请求以检查用户是否经过身份验证,如果是,我应该获取令牌。

我发现不推荐使用 Redux 核心 INIT 动作,那么在呈现应用程序之前如何调度动作?

原文由 Shota 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 504
2 个回答

2020 年更新:与其他解决方案一起,我使用 Redux 中间件来检查每个请求是否有失败的登录尝试:

 export default () => next => action => {
  const result = next(action);
  const { type, payload } = result;

  if (type.endsWith('Failure')) {
    if (payload.status === 401) {
      removeToken();

      window.location.replace('/login');
    }
  }

  return result;
};

2018 年更新:此答案适用于 React Router 3

我使用 react-router onEnter 道具解决了这个问题。这是代码的样子:

 // this function is called only once, before application initially starts to render react-route and any of its related DOM elements
// it can be used to add init config settings to the application
function onAppInit(dispatch) {
  return (nextState, replace, callback) => {
    dispatch(performTokenRequest())
      .then(() => {
        // callback is like a "next" function, app initialization is stopped until it is called.
        callback();
      });
  };
}

const App = () => (
  <Provider store={store}>
    <IntlProvider locale={language} messages={messages}>
      <div>
        <Router history={history}>
          <Route path="/" component={MainLayout} onEnter={onAppInit(store.dispatch)}>
            <IndexRoute component={HomePage} />
            <Route path="about" component={AboutPage} />
          </Route>
        </Router>
      </div>
    </IntlProvider>
  </Provider>
);

原文由 Shota 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以在 Root componentDidMount 方法和 render 方法中调度一个动作,您可以验证身份验证状态。

是这样的:

 class App extends Component {
  componentDidMount() {
    this.props.getAuth()
  }

  render() {
    return this.props.isReady
      ? <div> ready </div>
      : <div>not ready</div>
  }
}

const mapStateToProps = (state) => ({
  isReady: state.isReady,
})

const mapDispatchToProps = {
  getAuth,
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

原文由 Serhii Baraniuk 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进