ReactJS + Redux:在子Component中使用(功能)Component wrapper + dispatch(state)的无限渲染循环

时间:2017-09-06 16:10:26

标签: reactjs redux react-redux react-router-redux

我创建了一个无限的渲染循环,其中包含一个Component包装器和一个调用dispatch函数的子Component(用于更改redux中的状态),但我不明白为什么必须重新渲染此组件,因为props不会更改伊莫。

打包机:

export default function(ComposedComponent){
    class Authenticate extends Component {
        componentWillMount(){
            //If not logged in
            if (!this.props.loggedIn){
                this.context.router.history.replace({ pathname: '/login' });
            }
            console.log("Mount parent");
        }
        render(){
            return(
                    <ComposedComponent {...this.props} />
                );
        }
    }
    Authenticate.propTypes = {
        loggedIn: PropTypes.bool.isRequired
    }
    // Provide router in context for redirect 
    Authenticate.contextTypes = {
        router: PropTypes.object.isRequired
    }
    const mapStateToProps = state => ({
        loggedIn: state.user.loggedIn
    })

    return connect(mapStateToProps)(Authenticate);
}

子组件:

class InternalArea extends Component {
    componentDidMount(){
        this.props.setTitle(this.props.title);
        console.log("Mount child");
    }

    render(){

        return(
            <div>
                This is an internal area for logged in users.
            </div>
        );
    }

}
const mapDispatchToProps = dispatch => bindActionCreators({
        setTitle
    }, dispatch)

export default connect(
    null,
    mapDispatchToProps
 )(InternalArea);

Wrapper在App.js中被整合为一条路线(PropsRoute只传递额外的道具):

 <PropsRoute exact path="/internal-area" component={requireAuth(InternalArea)} title="Internal Area" />

删除子组件中的this.props.setTitle(this.props.title);解决了循环错误,但我需要在那里发送它。或者我应该搬家吗?为什么要更改道具?

1 个答案:

答案 0 :(得分:0)

最后,我想出了如何不使用功能包装器创建此循环,而是在App.js中接收Route Component作为子组件的Wrapper组件。建议使用此解决方案:https://www.cuttlesoft.com/infinitely-dispatching-actions-react-redux-react-router-v4/

尽管如此,我并不是100%理解为什么要创建这个循环。我有点困惑的是,函数包装器仍然是一种经常被建议的重定向方法,尽管它似乎不适用于在子组件中调度redux动作。