react生命周期componentDidMount中设置setState在esIint报错
项目背景
由于需要在页面渲染出来的时,对state中的数据进行初始化并需要出发render重绘
componentDidMount () {
let { selectedValue, stateValue } = this.state;
this.setState({
selectedValue,
stateValue,
});
}
运行结果
Do not use setState in componentDidMount react/no-did-mount-set-state
这里控制台报了个Waring,提示不要在componentDidMount中使用setState,想了下明白这个意思,componentDidMount 执行是在DOM渲染完成后,在这里面使用setState会触发重绘,打个比方,你明明知道正确的做法,却还是将错误方法执行了一次。。所以正确的使用就在页面第一次render前在constructor或者componentWillMount中把准备工作做好,推荐使用constructor。