首页 > 解决方案 > 是否可以在 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>
  )
}

currentSectionView是组件列表中的一项,当单击列表项中的任何一项时,它会向下传递。

记录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正在更新,但状态却没有。

所以基本上组件不会重新安装。它仅在所有内容第一次得到服务器渲染时才会安装。

那么,有什么办法可以重新安装它吗?

标签: javascriptreactjs

解决方案


从关于 constructor() 行为的React文档:

笔记

避免将道具复制到状态!这是一个常见的错误:

constructor(props) {
 super(props);
 // Don't do this!
 this.state = { color: props.color };
}

问题是它既是不必要的(您可以直接使用 this.props.color 代替),并且会产生错误(对 color 道具的更新不会反映在状态中)

仅当您有意忽略 prop 更新时才使用此模式。在这种情况下,将 prop 重命名为 initialColor 或 defaultColor 是有意义的。然后,您可以在必要时通过更改其键来强制组件“重置”其内部状态。

阅读我们关于避免派生状态的博客文章,了解如果您认为需要一些状态来依赖于 props,该怎么做。


推荐阅读