reactjs - 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
?
解决方案
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
.
推荐阅读
- r - 如何轻松生成多个具有两个以上变量的加权交叉表?
- asp.net - 消除 ”?” 来自 RadWindow 内容
- reactjs - 调用get()时reactjs通用cookie包错误
- c# - 文件权限,复制后c#
- javascript - 什么时候应该解构某些东西,什么时候不应该?JavaScript
- python - 自我机器人无法使用 cogs 运行功能?
- javascript - 难以重定向到 404 页面
- javascript - JSP Servlet 中的登录页面
- webrtc - 在阻止传出 UDP 连接的限制性防火墙后面访问 BigBlueButton
- python - 如何遍历字符串并变成字典