2017-05-23 34 views
1

我一直在學習ReactJS。在其文檔中,建議使用setState方法對組件進行任何更改,但也要在文檔中進行更改,不建議依賴「道具」,因爲「狀態」和「道具」異步工作。這是將數據傳遞給有狀態組件的正確方法嗎?

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

下面的例子是從文檔,但反一直沒有執行到這個例子,我自己做到了。 我想知道下面的方法是將數據傳遞給有狀態組件並在創建後更改其數據的正確方法。

class Clock extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = {date:new Date(),counter:parseInt(this.props.counter)}; 
    } 

    componentDidMount(){ 
     this.timerId = setInterval(() => this.tick(), 
     1000); 
    } 

    componentDidUnmount(){ 
     clearInterval(this.timerId); 
    } 

    tick(){ 

     this.setState((prevState,props)=>({ 
      date:new Date(), 
      counter:prevState.counter+1 
     })); 
    } 

    render(){ 
     return (
      <div> 
       <h1>Hello World</h1> 
       <h2>It is {this.state.date.toLocaleTimeString()} - {this.state.counter}</h2> 
      </div> 
     ); 
    } 
} 

ReactDOM.render(<div><Clock counter="0" /><Clock counter="10" /></div>,document.getElementById('root')); 

名爲「計數器」的屬性傳遞給組件,然後將其添加到在構造,之後的「狀態」,國家採取責任改變其數據。

我不明白那不是負責數據的「道具」嗎?我的方法是否真實和推薦?

回答

1

我的直覺是你沒有做錯任何事情。該文件說,你不應該依靠this.propsthis.state來計算下一個state。而事實上你避免更新狀態的先前狀態的功能:

this.setState((prevState, props) => ({ 
    date: new Date(), 
    counter: prevState.counter + 1 
})); 

這是做正確的方式,而這另一種方法是不正確的做法:

this.setState({ 
    date: new Date(), 
    counter: this.state.counter + 1 
}); 
至少在你將來的狀態取決於前一個狀態的情況下至少是

。您還正確地使用道具來啓動組件,因此您要傳遞想要用來初始化組件狀態的數據。這是完全正確的。之後,狀態將根據滴答功能進行收費並更改狀態。

相關問題