javascript - 是否可以在 React 中重新安装组件?
问题描述
所以我有一个顶级组件,它将更新的内容发送props
到所有子组件。
其中一个子组件在这样的组件中呈现如下View
:
const View = ({
currentSection
}) => {
console.log(currentSection.Component)
return (
<div>
<div className='main-content'>
<div className='sidenav'>
<div className='section'>
<h2 className='section-header'>My Login Page</h2>
</div>
</div>
<div>
{ currentSection.Component }
</div>
</div>
</div>
)
}
currentSection
View
是组件列表中的一项,当单击列表项中的任何一项时,它会向下传递。
记录currentSection
产量是这样的:
{Component: {…}, id: "members", label: "Members"}
以下是列表中组件之一的示例:
class Members extends React.Component {
constructor(props) {
super(props);
this.state = {
members: props.members
};
}
render() {
const { members } = this.state;
return <MembersList members={members} />;
}
}
您可以看到它是一个简单的组件,但奇怪的问题是props
正在更新,但状态却没有。
所以基本上组件不会重新安装。它仅在所有内容第一次得到服务器渲染时才会安装。
那么,有什么办法可以重新安装它吗?
解决方案
从关于 constructor() 行为的React文档:
笔记
避免将道具复制到状态!这是一个常见的错误:
constructor(props) {
super(props);
// Don't do this!
this.state = { color: props.color };
}
问题是它既是不必要的(您可以直接使用 this.props.color 代替),并且会产生错误(对 color 道具的更新不会反映在状态中)。
仅当您有意忽略 prop 更新时才使用此模式。在这种情况下,将 prop 重命名为 initialColor 或 defaultColor 是有意义的。然后,您可以在必要时通过更改其键来强制组件“重置”其内部状态。
阅读我们关于避免派生状态的博客文章,了解如果您认为需要一些状态来依赖于 props,该怎么做。
推荐阅读
- c# - 我想在激活 SelectionMode 时覆盖该行为
- flutter - Flutter 新项目构建错误 mergeDebugResources
- gradle - gradle 是否存储在 nexus repo 中?
- python - Python 如果打印结果与之前相同,则打印没有变化,否则打印新结果。每 10 分钟再跑一次
- android - 当我在谷歌播放控制台上发布我的应用程序包时出错
- javascript - 与 useState 的异步性质相比,React 的 useReducer 是同步的吗?
- jolt - 以下输入和预期输出所需的颠簸规范
- python - 插值到密度较小的网格 + Python 中的最小二乘拟合
- angular - 如何在角度材料中动态启用更新按钮
- haproxy - 我可以使用 HAProxy 转换传出请求吗?