Please explain in the main concepts that react doesn't refire componentDidMount even with conditional rendering and the solution is to use different keys
还没有人认领这个 Issue。
- 主要语言
- JavaScript
- 星标
- 11.8k
- 派生
- 7.9k
- 平均合并
- 1 天 11 小时
- 30 天内合并 PR
- 11
描述
As said by someone else here: "This should be way more obvious in the React documentation. This achieved exactly what I was after, but took hours to find."
This also took me hours to find that react doesn't automatically re-mount a component if the code is similar but just props change.
I was using conditional rendering doing:
var mycode = ""
if(a==true) {
mycode = <MyComponent myvar="true"/>
} else {
mycode = <MyComponent myvar="false"/>
}
And was expecting componentDidMount to fire to do crucial stuff, which obviously doesn't happen unless you specify a different key for both (solution at the bottom).
Please make this part of the Main Concepts of the React doc. The above linked answer got +190 upvotes which shows that this is a real problem for many coders.
Thank you very much for your consideration
Solution:
var mycode = ""
if(a==true) {
mycode = <MyComponent myvar="true" key="1"/>
} else {
mycode = <MyComponent myvar="false" key="2"/>
}
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 React 文档的 Main Concepts 部分开始,issue 将其确定为预期的切入点。说明带有已更改 props 的条件渲染不会重新挂载同一个组件,并记录 issue 中展示的 distinct-key approach;当读者能够清楚理解该行为和解决方案时,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, react
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 42/100