我知道这个问题已经被问过多次了, 但我仍然不知道如何修复我的代码。看来我不应该那样调用 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>
)
}
}
最佳答案
首先,如果没有index参数,使用bind的方式就可以了,如下:
this.handleStep = this.handleStep.bind(this);
onClick= {this.handleStep}
第二,如果onClick方法中有参数,则需要匿名函数来传递数据。匿名函数是()=>。
所以,使用箭头函数,你不需要在构造函数内部绑定(bind)。并且有很多选择:
//1
onClick={() => this.handleClick(index)}
//2
onClick={this.handleClick.bind(this, index)}
关于javascript - 无法在现有状态转换期间更新(例如在 `render` 内),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367165/