Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

image.png
PureComponent自带浅对比,如果不传thisval,React就认为About组件的props没变,所以不会更新


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...