react router 和 redux dispatch() 是来自所有路由的 运行 一次,而不是仅当前路由

react router and redux dispatch() is running from all routes once instead of only current route

我是 react 的新手,正在使用 react-router-dom@v4react-redux 构建应用程序。

App 组件如下所示:

    <Router>
        <Grid container>
            <Grid item xs={12}>
                <Header/>
            </Grid>
            <Grid item xs={12}>
                <Route exact path="/" component={Dashboard}/>
                <Route path="/admin" component={Admin}/>
            </Grid>
        </Grid>
    </Router>

并且 Root 文件呈现为:

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root'));

现在的问题是:

  1. 两条路线包含相同的 store.dispatch,但值不同:

  2. 第一条路线/

     store.dispatch({type: "active": payload: 1})
    
  3. 第二条路线/admin

     store.dispatch({type: "active": payload: 0})
    

现在,当应用程序 运行s 在索引路由 / 上时,它 运行s dispatch() 并给出值 1... 正确。 但之后它也 运行 来自另一条路线 /admindispatch() 并将值更新为 0... 我不想要的..

我想要的:

当我在该路线上时,该应用程序应该 运行 dispatch() 所有路线都没有一次。

任何帮助将不胜感激:

:)

干杯。

终于找到了如何避免运行 dispatch() once from all routes这个问题的答案

只需将 store.dispatch() 放入 ReactJS 组件的生命周期挂钩中,就像放入 componentDidMount() 一样,它只会在用户使用 Component/route 时调用。

下面是一个例子:

componentDidMount() {
    store.dispatch({type: "active", payload: 0});
}