状态未在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)和值记录。但我必须将其保存到构造函数中,以将其传递给另一个组件。

问题是状态没有改变。

我在做什么错了?

在此先感谢

+0

顺便说一句你为什么要把dom元素引用到组件的状态? –

+0

我需要抵消div – Giedrius

+0

[this.setState不更新值可能的重复](https://*.com/questions/41278385/this-setstate-doesnt-update-value) –

setState是异步。 Docs。如果你想看到更新的状态使用回调。

componentDidMount() { 
     this.setState({ 
      el: this.refs.el 
     },() => console.log(this.state.el)); 
    } 
+0

这是伟大的,但为什么我必须为了设置状态而使用console.log(),是否可以在没有console.log的情况下进行回调? – Giedrius

+0

@Giedrius你不必记录。这只是如果你想使用**更新**状态,你需要使用回调。但是,这完全取决于你想要做什么新的状态 –

+0

好吧,最后一个问题,然后,我如何将更新的状态作为道具传递给另一个组件?我也必须使用回调函数 this.state.el”/>? – Giedrius

就像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已完成这将现在只渲染。