react-redux高阶组件不会重新渲染的问题
问题:为什么基组件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);
回答
PureComponent
自带浅对比,如果不传thisval
,React就认为About
组件的props没变,所以不会更新
以上是 react-redux高阶组件不会重新渲染的问题 的全部内容, 来源链接: utcz.com/a/98466.html