3
votes

i have a problem, i want dispatch my action(isLoading) before my component in route render, but when i call dispatch in onEnter event React gives error:

"Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount."

I understant this error is logic result, because i mutate my data in store when component rendering, i can't put dispatch in componentDidMount because Route child rendering before i get componentDidMount in parent component Route(. Plsease help me), i need good solution for this case.

My code: `

const App = ({ location }) => {
  return (
        <div>
          {console.log(this)}
          <TransitionGroup className="transition-group">
            <CSSTransition
                key={location.key}
                timeout={0}
                classNames="fade"
            >
              <section className="route-section">
                <Switch location={location}>
                  <Route path="/" exact component={Index} onEnter= 
                       {store.dispatch(isLoading(true))}/>
                  <Route path="/news" exact component={News}/>
                  <Route path="/projects" exact component={Projects}/>
                  <Route path="/contacts" exact component={Contacts}/>
                  <Route path="/about"  exact component={About}/>
                </Switch>
              </section>
            </CSSTransition>
          </TransitionGroup>
        </div>
  )
};

`

1

1 Answers

0
votes

I think you need to wrap the dispatch in a function and not call it directly, like this (assumes you're working with ES6 syntax):

onEnter={() => store.dispatch(isLoading(true))}

Also, note that in react-router 4 the onEnter property is no longer supported, see https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/migrating.md#on-properties.