状态未在componentDidMount中设置
问题描述:
我想从渲染函数访问ref,并将其设置为状态。状态未在componentDidMount中设置
这里是我的代码:
export default class App extends Component {
constructor(props) {
super();
this.arr = this.generateTimelineArray();
this.state = {el : 'empty'};
}
componentDidMount() {
this.setState({
el: this.refs.el
});
console.log(this.state.el)
}
render() {
return (
<div className="timeline__container--line" ref="el" ></div>
);
}
我可以console.log(this.refs.el)
和值记录。但我必须将其保存到构造函数中,以将其传递给另一个组件。
问题是状态没有改变。
我在做什么错了?
在此先感谢
答
setState
是异步。 Docs。如果你想看到更新的状态使用回调。
componentDidMount() {
this.setState({
el: this.refs.el
},() => console.log(this.state.el));
}
答
就像Yury说的那样,this.setState
是异步的。除了一个回调函数,你可以使用一个布尔状态变量和检查,在渲染:
export default class App extends Component {
constructor(props) {
super();
this.arr = this.generateTimelineArray();
this.state = {el : 'empty', flag : true};
}
componentDidMount() {
this.setState({
el: this.refs.el,
flag : false
});
console.log(this.state.el)
}
render() {
return (
this.state.flag == false &&
<div className="timeline__container--line" ref="el" ></div>
);
}
一旦异步的setState已完成这将现在只渲染。
顺便说一句你为什么要把dom元素引用到组件的状态? –
我需要抵消div – Giedrius
[this.setState不更新值可能的重复](https://stackoverflow.com/questions/41278385/this-setstate-doesnt-update-value) –