问题:为什么基组件HighComponent重载时,父组件About会时不时进不了render?
HighComponent.js文件
import React, { PureComponent } from 'react';
import store from '../store/index';
function HighComponent(Component) {
return class extends PureComponent {
constructor(props) {
super(props);
this.state = {
thisval: store.getState().thisval,
};
}
componentDidMount() {
this.UnSubscribe = store.subscribe(() => {
console.log(2, store.getState().thisval);
this.setState({ thisval: store.getState().thisval });
});
}
componentWillUnmount() {
this.UnSubscribe();
}
render() {
console.log(3);
return <Component
{...this.props}
// 问题:只有加上此句时,重载render时,才会进入父组件的render函数,为什么?
// thisval={this.state.thisval}
/>;
}
};
}
export default HighComponent;
about.js文件
import React from 'react'
import { PureComponent } from 'react';
import store from '../store/index';
import { addAction } from '../store/actionCreators';
import HighComponent from '../utils/HighComponent';
class About extends PureComponent {
render() {
console.log(4);
return <div>
<h2>about</h2>
<div>thisval:{store.getState().thisval}</div>
<div>
<button onClick={() => store.dispatch(addAction(1))}>+1</button>
<button onClick={() => store.dispatch(addAction(5))}>+5</button>
</div>
</div>
}
}
export default HighComponent(About);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…