【问题标题】:Cannot update during an existing state transition (such as within `render`)在现有状态转换期间无法更新(例如在 `render` 中)
【发布时间】:2018-11-19 09:54:17
【问题描述】:

我知道这个问题已经被问过多次了, 但我仍然不知道如何修复我的代码。好像我不应该那样调用 setState 。但是我从material-ui网站上获取了示例代码,这应该是直截了当的吗?

class Dashboard extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            activeStep: 0,
        }
        this.handleStep = this.handleStep.bind(this);
    }

    handleStep(step) {
        this.setState({activeStep: step});
    };

    render(){
        const { classes, match } = this.props;
        const sprints = ['sprint 1', 'sprint 2', 'sprint 3'];
        const { activeStep } = this.state;

        return (
            <div className= {classes.root}>
                <div className = {classes.container} > 
                    <Stepper nonLinear activeStep={activeStep} alternativeLabel>
                        {sprints.map((label,index)=>
                            {
                                return (
                                    <Step key={label}>
                                        <StepButton
                                            onClick= {this.handleStep(index)}
                                        >
                                            {label}
                                        </StepButton>
                                    </Step>   
                                )
                            })
                        }
                    </Stepper>
                </div>
            </div>
        )
    }
}

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    首先,如果你没有index参数,你使用bind的方式是可以的。像这样:

    this.handleStep = this.handleStep.bind(this);
    onClick= {this.handleStep}
    

    其次,如果onClick方法中有参数,则需要匿名函数来传递数据。匿名函数是()=>。

    所以,有了箭头函数,你就不需要在构造函数里面绑定了。而且有很多选项:

    //1
    onClick={() => this.handleClick(index)}
    //2
    onClick={this.handleClick.bind(this, index)}
    

    【讨论】:

      【解决方案2】:

      StepButton 中的 onClick 应该是 onClick={() =&gt; this.handleStep(index)}。注意箭头功能。这会传入一个回调函数,该函数将在触发onClick 时运行,而您的代码在render 期间调用this.handleStep。否则,您处理状态更新的方式非常好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多