2016-12-02 48 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会在屏幕出现之前更新。