forceUpdate不会重新呈现子项

时间:2016-06-26 00:45:31

标签: reactjs redux react-router

我正在为我的webapp使用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发生时,子组件不会被重新渲染。

2 个答案:

答案 0 :(得分:0)

我想我明白了。每个容器组件应分别订阅商店。因此,ContentPage也应该有

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

答案 1 :(得分:0)

当您回复yourself时,容器组件确实应该订阅商店,但除了订阅之外,容器在<取消订阅时也是一种好习惯。 strong> un 已安装:

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

componentWillUnmount() {
  this.unsubscribe();
}