是否可以在React中重新安装组件?

时间:2018-06-30 01:49:02

标签: javascript reactjs

因此,我有一个顶级组件,它将更新的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正在更新,但状态却没有。

因此基本上不需要重新安装组件。仅当所有内容都首次呈现在服务器上时,它才会挂载。

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

2 个答案:

答案 0 :(得分:1)

从React documentation中了解有关builder()行为的信息:

  

注意

     

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

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

问题在于,两者都是不必要的(您可以使用   而是直接使用this.props.color),并创建错误(更新为   彩色道具将不会反映在状态中)

     

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

     

阅读有关避免派生状态的博客文章,以了解该怎么做   如果您认为需要某种状态来依赖道具。

答案 1 :(得分:0)

在React 16.3+中,您可能需要componentWillRecieveProps生命周期方法或静态方法getDerivedStateFromProps