2017-07-08 61 views
1

我想從渲染函數訪問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://stackoverflow.com/questions/41278385/this-setstate-doesnt-update-value) –

回答

3

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

0

就像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已完成這將現在只渲染。