【问题标题】:React js lifecycle methods not firing on wrapped componentReact js生命周期方法未在包装组件上触发
【发布时间】:2017-05-23 18:02:24
【问题描述】:

这是一个组件:

export default class MyComponent extends React.Component {
  componentWillReceiveProps(newProps) {
    console.log('RECEIVED PROPS');
  }

  render() {
    return <div>{this.props.foo}</div>
  }
}

这是一个包装器/高阶组件​​:

  const withSomething = (ComponentToWrap) => {
    render() {
      return <ComponentToWrap {...this.props} />
    }
  }

这是一个将 MyComponent 包装在 withSomething 中的功能组件:

export default function WrappedComponent(props) {
    const Component = withSomething(MyComponent);
    return <Component ... some props ... />
}

结果:MyComponent 中与 props 相关的生命周期函数(例如 componentWillReceiveProps)永远不会触发,即使我更新了 props。

这是怎么回事?基于 props 的生命周期方法是否不适用于包装的组件?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    问题在于,由于创建被包装组件的行包含在功能组件中,因此基本上每次功能组件渲染时都会创建一个新组件。

    这一行最终被包含在 WrappedComponent 的渲染方法中:

    const Component = withSomething(MyComponent);
    

    ...这意味着组件在每次渲染时都会被覆盖。

    另一条线索是将 componentDidMount() 放入 MyComponent ——它会在每次 props 更新时触发。

    解决方案是在功能组件之外的某处创建包装组件,如果您使用的是常规类组件,则在渲染方法之外创建。

    【讨论】:

      猜你喜欢
      • 2015-08-26
      • 2016-01-13
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      相关资源
      最近更新 更多