高阶分量

Higher Order Component

A/t 到 Docs,HOC 不会修改输入组件,也不会使用继承来复制其行为。相反,HOC 通过将其包装在容器组件中来组合原始组件。

在 React 中,如果 props 发生变化,组件将使用 newProps 重新渲染。

因为在 HOC 中,我们将 props 传递给包装器组件 test1 和 test2,所以它们都应该在每次 props 更改时重新渲染。但这并没有发生。事实上,test1 和 test2 被渲染,然后 test2 通过状态提升和重新渲染来改变道具。但 test1 保持不变。 检查附件图像。

我很想知道 react-redux connect 和 react-router-dom withRouter 实际上是如何处理每个 props 更改以存储和重新渲染组件的。

Real Problem on Github

class Test extends React.Component {
  render() {
    return (
      <div>
        <Test1 />
        <Test2 />
      </div>
    )
  }
}

含HOC的组件

class Test1 extends React.Component {
  render() {
    return(
      <div>
          {
              this.props.test1
          }
          {
              this.props.test2
          }
      </div>
     )
  }
}
export default withHOC(Test1);

另一个带有HOC的组件

class Test2 extends React.Component {
  render() {
    return(
      <div>
        {
            this.props.test1
        }
        {
            this.props.test2
        }
        <button type='button' onClick={()=>this.props.update('test')}>Update </button>
      </div>
    )
  }
}
export default withHOC(Test2);

高阶分量

function withHOC(WrappedComponent) {
  class Test extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
          test1: 'test1',
          test2: 'test2'
      }
    }
    update = (u) => {
      this.setState({
          test2: u 
      })
    }
    render() {
      const test1 = this.state.test1;
      const test2 = this.state.test2;
      return (<WrappedComponent test1={test1} test2={test2} update={this.update}/>);
    }
  }
  return Test;
}
export default withHOC;

Log of Life Cycle Methods

首先,你没有在这里真正提出问题 - 这个 post 的标题应该重写以便真正提出问题。

我说您正在尝试使用 HOC 在两个组件之间共享状态是否正确?然后期望 <Test2 /> 中的更新导致 <Test1 /> 中的更新,因为 <Test2 /> 上的 props.test2 已更改?

如果是这样,那么这是对 HOC 的错误思考方式。将 HOC 视为具有特定属性或行为的 装饰 组件。您问题中详细说明的 withHOC 的使用不是说 "let any component wrapped in withHOC access the single piece of state defined in this HOC",而是说 "any component wrapped in withHOC should have its own state defined by the functions given in this HOC".

因此包装两个组件,然后在 <Test2 /> 中更改状态,只会更改该特定组件中的状态。

如果您希望 <Test2 /> 中的更新导致 <Test1 /> 中的更新,则必须使用 parent 组件的状态(即 <Test /> ).