2016-12-02 45 views
4

我正在使用React Native的導航器。無論如何刷新組件,所以當我回到它,它會進行一個新的API調用,並獲取更新的數據顯示在組件中。我發現了一些類似的問題,但沒有好的答案...刷新導航器上的組件()

回答

1

您應該保存頁面的state,並在componentDidMount中發出一個動作,因爲它在組件裝入後立即被調用。

參考文獻:

  1. https://facebook.github.io/react/docs/react-component.html
  2. https://github.com/ReactTraining/react-router

ADDED

由於您的組件已被安裝,你應該聽ComonentWillReceiveProps代替。

+0

上一個組件已經掛載,所以當你彈出它時不會再次調用componentDidMount。 –

+0

這是有道理的,你應該能夠鉤住你的ComponentWillReceiveProps嗎? https://gist.github.com/agrcrobles/ba6832a3ecf8c8c47c0c4101aa0a2ffe – locropulenton

+0

我想出了一個解決方案,讓它按照我想要的方式工作,只是希望有一個像其他生命週期方法一樣可以調用的OnFocus。 –

1

您可以將回調函數作爲道具發送到nextScene中的nextscene。

this.props.navigator.push({ 
      name: *nextscene*, 
      passProps: { 
      text: response, 
      callBack: this.callback 
     }); 

async callback(){ 
    await ....//make new api request grab the udpated data 
} 

然後在你的nextscene中調用回調方法,然後彈出。您還可以發送參數

this.props.callBack() 
this.props.navigator.pop() 
2

當pop()方法來刷新前一個頁面是不是一個好主意

您可以嘗試DeviceEventEmitter對象

  • 上一頁DeviceEventEmitter.addListener('xxx', callback)componentDidMount
  • 電流第DeviceEventEmitter.emit('xxx', anythingInCallback...)之前pop()

PS:前一頁DeviceEventEmitter.removeAllListeners('xxx')componentWillUnmount

0

我懷疑你還在尋找一個答案,但哇靠這已經讓我今晚。我對React Native很新,但我終於取得了一些成功。

React Navigation API docs有添加事件監聽器的部分!一探究竟!我也在下面分享了我自己的一些代碼。

這是組件中的示例事件處理程序,它是StackNavigator堆棧的頂部屏幕。它抓取當前狀態並使用API​​調用保存到後端。完成後,調用StackNavigator的彈出窗口。

handleSubmit =() => { 
    const { value, otherValue } = this.state 
    addThingToDatabase({ value, otherValue }) 
    .then(() => this.props.navigation.pop()) 
} 

現在轉到另一個組件,它是StackNavigator堆棧中「下方」的屏幕。這是在「流行」之後顯示的屏幕。以下是我在中曾使用過的ComponentDidMount中的

componentDidMount() { 
    const { index } = this.props.navigation.state.params 

    getAllThingsFromDatabase({ index }) 
    .then(({ arrayOfThings }) => this.setState({ 
     index, 
     arrayOfThings 
    })) 
} 

但是,組件不會更新新的東西,直到addListener!現在我有幾乎相同的代碼,除了它在構造函數中。我想我只需要運行一次,我也需要存儲它。

constructor(props, context) { 
    super(props, context) 

    this.state = { 
    index: null, 
    arrayOfThings: [] 
    } 

    this.willFocusSubscription = this.props.navigation.addListener(
    'willFocus', 
    (payload) => { 
     const { index } = payload.state.params 
     getAllThingsFromDatabase({ index }) 
     .then(({ arrayOfThings }) => this.setState({ 
      index, 
      arrayOfThings 
     })) 
    } 
) 
} 

請注意,文檔還提到使用.remove()函數取消訂閱事件偵聽器。我把它放在ComponentWillUnmount()

componentWillUnmount() { 
    this.willFocusSubscription.remove() 
} 

有四種不同的事件要訂閱。我認爲willFocus會在屏幕出現之前更新。