Reputation: 1009
I am new to react
and building an app using react-router-dom@v4
and react-redux
.
The App component looks like as:
<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>
and the Root file is rendering as:
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
Now the problem is:
Both routes contains same store.dispatch
with different values as:
The first route /
store.dispatch({type: "active": payload: 1})
The second route /admin
store.dispatch({type: "active": payload: 0})
Now when the application runs on the index route /
it runs dispatch()
and gives value 1
... correct.
but afterward It also run the dispatch()
from the other route /admin
and updates the value to 0
... which I don't want..
What I want:
That application should run dispatch()
when I'm on that route not once from all routes.
any help would be appreciated:
:)
cheers.
Upvotes: 1
Views: 195
Reputation: 1009
At last, I have found the answer to this question that how to avoid the problem that running dispatch()
once from all routes.
Simply put the store.dispatch()
in the lifecycle hook of the ReactJS Component like putting in componentDidMount()
would work and it would only call when a user is on that Component/route.
Here is an example below:
componentDidMount() {
store.dispatch({type: "active", payload: 0});
}
Upvotes: 1