首页 > 解决方案 > Why don't redux actions "break" componentDidMount/useEffect?

问题描述

A component will rerender when one of its props changes. That's sort of the whole point of React.

A component that's subscribed to a slice of Redux state will rerender when that state changes. That's sort of the whole point of Redux. And when you use the connect api, those slices of state are simply props, so it goes straight to my first point.

SO, what I'm wondering is:

// only executes once, on mount, right?
componentDidMount() {
  this.something()
  this.props.someReduxActionThatModifiesAnotherPropInThisComponent()
  this.somethingElse()
}

Since the redux action changes the prop, and the component rerenders, I would think that componentDidMount has had its day and now it's done, and we'll never run this.somethingElse().

Obviously I am wrong about this. I know. Can someone tell me what it is that makes this work? What is the whole flow here? I imagine the answer is maybe simply that a component doesn't rerender from inside CDM?

And is it any different in useEffect?

标签: reactjsredux

解决方案


You are correct that componentDidMount only runs once. You are also correct that dispatching a redux action from within the method will trigger a re-render if your component is subscribed.

I think the confusion is about when a re-render occurs.

Updating state only informs React that a re-render is required, it does not pause execution and re-render immediately.

Because of this, the lifecycle method will complete execution of the entire method, and the run the scheduled re-render after.

This is related to why you also cannot use the updated state immediately after calling this.setState (or dispatch in Redux). Because the state is not updated instantly, you've only informed it that an update is required. Behind the scenes, React batches and performs the updates, and then determines what re-renders to perform.

The same is true about Function components and useEffect.


推荐阅读