无限循环Redux / React

时间:2018-06-03 13:39:42

标签: javascript reactjs asynchronous react-redux

大家好我有主要组件包装另一个组件。

<Configuration>
    <Switch>
      .....
    </Switch>
</Configuration>

如果配置容器我使用connect:

const mustBe = ['menu'];

function mapStateToProps (state) {
  return {...state.configuration}
}


function mapDispatchToProps(dispatch){
    return {
        actions: bindActionCreators({
            ...upload
        }, dispatch),
        dispatch
    }
}

class Configuration extends React.Component {

    constructor(props, context){
        super(props, context);

        this.state = {uploaded: false}

    }

    componentDidMount(){

        for(let key of mustBe){

            if(!this.props[key] || !Object.keys(this.props[key]).length ){
                this.props.actions.upload()
            }
        }

    }

    componentWillReceiveProps(){
        this.setState((state) => {
            return {uploaded: true}
        })
    }


    render(){

        if(!this.state.uploaded) return null;

        return {this.props.children};
        )
    }
}

Configuration.contextTypes = {
    router: PropTypes.object
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Configuration));

配置有自己的减速器,由菜单组成,例如:

import menu from './menu.rd.js';


const Configuration = combineReducers({
  menu
});

很简单。

我也有Menu组件也使用connect:

function mapStateToProps (state) {
  return {...state.configuration.menu}
}

function mapDispatchToProps(dispatch){
    return {
        actions: bindActionCreators({
            ...menu
        }, dispatch),
        dispatch
    }
}


class Menu extends React.Component {
    constructor(props, context){
        super(props, context);
    }

    componentDidMount(){

        let {pathname} = this.context.router.route.location;
        this.props.actions.changed(pathname);

    }

    render(){

        return (
            ...
        )
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Menu); 

问题是:重启之后,所有从容器开始,我加载菜单项并渲染子组件。

子组件包含componentDidMount和render方法,在组件呈现后调用componentDidMount并更改store中的状态。

再次调用componentWillReceiveProps并渲染。

在组件调用Render和componentDidMount中再次改变状态。

它无限循环。你用它做什么? 为什么componentDidMount一直调用render?

1 个答案:

答案 0 :(得分:0)

[关闭]

我明白了。我在Router中使用了loop并且总是调用Component

相关问题