2017-05-23 47 views
1

上。這裏JS生命週期方法是一個組件:陣營未擊發裹組件

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的功能部件in withSomething:

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

結果:與道具相關的生命週期函數(如componentWillReceiveProp s)在MyComponent中永遠不會開火,即使我更新道具。

這是怎麼回事?基於道具的生命週期方法不適用於包裝組件嗎?

回答

2

問題是,由於創建包裝組件的行包含在功能組件中,因此每次功能組件呈現時都會創建一個新組件。

這條線最終被列入WrappedComponent的渲染方法:

const Component = withSomething(MyComponent); 

...這意味着組件被在每一個渲染覆蓋。

另一個線索是將componentDidMount()放入MyComponent中 - 每當道具更新時它都會觸發。

解決方案是在功能組件外的某處或者在使用常規類組件的渲染方法外部創建包裝組件。