[英]React js lifecycle methods not firing on wrapped component
這是一個組件:
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)也不會觸發。
這怎么了? 基於道具的生命周期方法不適用於包裝組件嗎?
問題在於,由於創建包裝組件的行包含在功能組件中,因此每次功能組件呈現時它基本上都會創建一個新組件。
該行最終包含在WrappedComponent的render方法中:
const Component = withSomething(MyComponent);
...這意味着在每次渲染時都會覆蓋Component。
另一個線索是將一個componentDidMount()放入MyComponent中 - 每次更新道具時它都會觸發。
解決方案是在功能組件外部的某處創建包裝組件,如果使用常規類組件,則在render方法之外創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.