【问题标题】:forceUpdate is not re-rendering childrenforceUpdate 不会重新渲染子级
【发布时间】:2016-06-26 00:45:30
【问题描述】:

我正在为我的 web 应用程序使用 react、redux react-router 堆栈。在顶层组件(在根路径上渲染的组件)componentDidMount我订阅了商店,如下所示

import NotificationsList from './components/notifier';
import React from 'react';

let Spinner = ({
    isVisible,
    showSpinner,
    solidBackdrop
}) => (
    <div style={{opacity: solidBackdrop ? 1 : 0.5}} className={"spinner " + (isVisible ? '' : 'hide')}></div>
);

export default class AppPage extends React.Component {
    static contextTypes = {
        store: React.PropTypes.object,
        router: React.PropTypes.object
    };

    handleDismissNotification(notification) {
        this.context.store.dispatch({
            type: 'REMOVE_NOTIFICATION',
            data: notification
        });
    }

    componentDidMount() {
        this.context.store.subscribe(() => this.forceUpdate());
    }

    render() {
        let state = this.context.store.getState();
        let props = {
            notifications: state.notifications,
            handleDismiss: this.handleDismissNotification.bind(this)
        };
        return (
            <div className="'apppage-container">
                {this.props.children}
                <NotificationsList {...props} />
                <Spinner isVisible={state.initialFetchInProgress || state.requestInProgress}
                         showSpinner={!state.initialFetchInProgress} solidBackdrop={state.initialFetchInProgress}/>
            </div>
        );
    }
}

this.props.children这里渲染组件如下图

import Header from './components/header';
import React from 'react';

class ContentPage extends React.Component {
    static contextTypes = {
        store: React.PropTypes.object
    };

    render() {
        let user = this.context.store.getState().user;
        return <div className="content-container">
            <Header user/>
        </div>
    }
}

export default ContentPage;

问题是当第一次渲染发生时,一切都很好。然后,当通过forceUpdate 进行渲染时,子组件不会重新渲染。

【问题讨论】:

  • 我对 react 不太熟悉,但我相信您需要提供商店的内容才能解决此问题。

标签: reactjs redux react-router


【解决方案1】:

我想我明白了。每个容器组件都应该单独订阅到 store。所以相应地,ContentPage 也应该有

componentDidMount() {
    this.context.store.subscribe(() => this.forceUpdate());
}

【讨论】:

    【解决方案2】:

    正如你回复yourself,容器组件确实应该订阅 store ,但是除了订阅之外,容器最好也un在 时订阅未安装:

    componentDidMount() {
        this.unsubscribe = this.context.store.subscribe(() => this.forceUpdate());
    }
    
    componentWillUnmount() {
      this.unsubscribe();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2020-02-13
      • 2020-04-18
      • 2018-12-28
      • 1970-01-01
      • 2017-05-31
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多