React js生命周期方法不会在包装组件上触发

时间:2017-05-23 18:02:25

标签: javascript reactjs

这是一个组件:

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中与道具相关的生命周期函数(例如componentWillReceiveProps)也不会触发。

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

1 个答案:

答案 0 :(得分:5)

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

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

const Component = withSomething(MyComponent);

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

另一个线索是将一个componentDidMount()放入MyComponent中 - 每次道具更新时它都会触发。

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