因爲你還沒有規定如何根據我所做的問題調用您的高階組件猜猜你會如何使用它。
我的回答是基於你調用像
var MyHigherOrderFn = (HigherOrderComponent(Baar));
您的高階函數的假設。如果有些你怎麼可以調用您的高階函數類似下面爲return
在render
,你可以迴避的問題。
<HigherOrderComponent prop1="Hello" child="Child" />
因爲我不;知道如何在上面的方式調用你的函數(我不知道它甚至有可能),我創建HigherOrderComponent2
不同的語法格式可以調用一樣,這又符合shouldComponentUpdate
<Parent prop1="val1">
<Child>
</Parent>
import React, {PropTypes} from 'react';
/*This is simeple child component*/
class Baar extends React.Component {
render() {
return (<div>{this.props.name}</div>);
}
}
/*This is your higher order component*/
const HigherOrderComponent = Component => class extends React.Component {
shouldComponentUpdate (nextProps, nextState) {
return false;
}
render() {
return <Component {...this.props} />
}
}
/*This is another way to write higher order component*/
class HigherOrderComponent2 extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate (nextProps, nextState) {
return false;
}
render(){
let child = this.props.children && React.cloneElement(this.props.children,
{...this.props}
);
return <div>{child}</div>
}
}
/*Problem that you are facing how you invoke your Higher Order Compoent*/
export default class Foo extends React.Component {
constructor(props) {
super(props);
this.onHandleClick = this.onHandleClick.bind(this);
this.state={
name: 'Praveen Prasad'
}
}
onHandleClick(){
this.setState({
name:Math.random()
});
}
render() {
{'This is how you might be invoking you higher order component, at this time react render doesnt know it already exists in DOM or not'}
{'this component will always re-render, irrespective of values in shouldComponentUpdate'}
var Baaz = (HigherOrderComponent(Baar));
return (<div>
<button onClick={this.onHandleClick}>Update Name</button>
<Baaz name={this.state.name} />
{'This is another way to invoke higher order Component , and this will respect shouldComponentUpdate'}
<HigherOrderComponent2 name={this.state.name}>
<Baar />
</HigherOrderComponent2>
</div>);
}
}
總要得到重新呈現什麼時候? –
你好,我根據你的組件編寫了一些代碼,發現你確實是對的。讓我看看我們該如何解決這個問題。 –