【发布时间】:2017-02-13 01:18:10
【问题描述】:
我有一个组件,我在 componentDidMount 函数中更新了状态。我收到一条 linter 警告,将我指向此页面:
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
它说
防止在componentDidMount(no-did-mount-set-state)中使用setState
在组件挂载后更新状态将触发第二次 render() 调用,并可能导致属性/布局抖动。
我应该在哪里更新我的状态?
这是我的 componentDidMount 函数:
componentDidMount(){
this.interval = setInterval(() => {
this.setState({
frame: this.state.frame + 1
});
}, this.props.interval);
}
这是我的渲染函数:
render(){
let dots = this.state.frame % (this.props.dots + 1);
let text = '';
while(dots > 0){
text += '.';
dots--;
}
return <span {...this.props}>{text} </span>;
}
我的构造函数:
constructor(props, context){
super(props, context);
this.state = {frame: 1};
}
【问题讨论】:
-
构造函数呢?
标签: reactjs