2016-10-21 79 views
-2

當我試圖更新來自componentwillmount函數中的api調用的反應組件的狀態它不按預期工作。該值沒有設置。狀態不更新componentWillMount

export default class ListOfProducts extends Component { 
     componentWillMount() { 
      console.log('component currently mounting'); 
      fetchOrder().then(data => { 
       console.log('order api call has been finished.', data); 
       this.setState(data, function() { 
     //this should print new data but i am still getting old data 
        console.log('current this.state.', this.state.orders) 
       }) 
      }) 
     } 
     constructor(props) { 
      super(props); 

      this.state = { 
       "orders": { 
        "order_items": [] 
       } 
      }; 
     } 
     render() { 
      let productList = []; 
      let productUnit = (
       <View> 
      {this.state.orders.order_items.map(function(order,i){ 
      return <ProductListItem 
       delivered={true} 
       productSKU={3}/> 
      })} 
      </View> 
      ); 
      return productUnit; 
     } 
    } 
+0

我不知道,但我認爲你可以直接修改狀態componentWillMount因爲組件沒有渲染它是沒有意義的調用setState或打電話給setState是componentDidMount – Barry127

+0

即使this.state =數據不工作 –

+0

@RakeshYadav你不應該手動設置任何值爲'this.state',因爲他們當你調用setState()時會被覆蓋。 –

回答

2

如果要執行任何異步請求,我建議你在componentDidMount生命週期的方法來執行它們。這是基於Reactjs documentation for componentDidMount的建議路徑。

在初始渲染髮生後,僅在客戶端(不在服務器上)調用一次,立即調用 。在生命週期的這一階段,您可以訪問任何參考給您的孩子(例如,訪問底層DOM表示)。子組件的componentDidMount()方法在子組件的父組件之前被調用。

如果您想要與其他JavaScript框架集成,請使用setTimeout或setInterval設置定時器 ,或發送AJAX請求,請在此方法中執行那些 操作。

0

也許你需要改變: 「擴展組件{」 到 「擴展React.Component {」

+0

嗨,歡迎來到StackOverflow。當您發佈答案時,請確信它會解決問題。如果您不確定並且仍想發佈您的想法,請嘗試描述爲什麼您認爲它可以解決問題。祝你好運! –