如何从react-hook onEnter hook连接到redux store?

时间:2015-11-02 22:20:01

标签: reactjs react-router redux

我想在路由加载时使用react-router的onEnter挂钩检查我的redux存储中的变量。

根据文档,onEnter

  

...接收下一个路由器状态作为其第一个参数。 replaceState函数可用于触发向其他URL的转换。

没有商店通过。是否可以从此钩子中连接到redux存储?我已经尝试了各种各样的东西,但找不到实现这个目标的方法。

我正在使用的版本:

"react-redux": "^4.0.0",
"react-router": "1.0.0-rc1",
"redux": "^3.0.0",

3 个答案:

答案 0 :(得分:11)

使路线成为一个将商店置于参数

中的功能
export default (store) => {
 return (
  <Route handler={App} path="/">
    <Route path="mypath" component={handler} onEnter={myHook(store)}>
  <Route>
 )
};

在转换挂钩中执行相同的操作

export const myHook = (store) => {
  return (location, replaceWith) => {
    // Do something with your store
  }
};

然后假设您在同一个文件中创建商店和路由器

const router = (
            <Provider store={store}>
                <Router history={history}>
                    {routes(store)}
                </Router>
            </Provider>
        );

答案 1 :(得分:4)

您可以创建文件store.js并导出最终商店(与传递给redux的相同)

E.g。

import configureStore from 'utils/configure-store.js';

const store = configureStore();
export default store;

然后导入到路由器文件并按store.getState()

读取状态

答案 2 :(得分:1)

React Router {4}的第4版建议使用组件生命周期方法来处理更改。

例如,使用componentWillMount代替onEnter或通过componentWillReceiveProps回复状态更改。

所以在您的组件本身:

import { browserHistory } from 'react-router';

...

componentWillMount() {
  if (someConditionIsTrue) {
    browserHistory.push('/your/new/path');
  }
}

对于奖励积分,您可以将其写为migration documentation,简单地包裹原始组件。更容易在需要相同行为的任何其他组件之间共享此逻辑。