React Native:使用Navigator didFocus事件

时间:2016-07-14 00:09:09

标签: javascript reactjs callback react-native

注意:我设法在不使用EventEmitters和subscribables的didFocus事件的情况下解决问题。因为该解决方案没有回答这个特定问题(如何使用didFocus事件),所以我在另一个问题上发布了solution

我有一个带有_refreshData方法的ListView,该方法在componentDidMount上调用。该方法对领域数据库进行简单查询,并相应地刷新ListItem:

在我的<FooListScreen>组件

componentDidMount(){
    this._refreshData();
}

_refreshData(){

    this.setState({
        dataSource: this.state.dataSource.cloneWithRows(realm.objects('Foo'))
    })

}

我希望在保存一个新的&#39; Foo&#34;的实例后能够致电_refreshData()从我推到Navigator堆栈的表单组件。保存新的Foo后,我会navigator.pop()返回<FooListScreen>组件并以某种方式重新呈现ListView。经过一些阅读,似乎最好的做法是使用导航器的didFocus事件回调,但我找不到一个有用的代码示例。有什么想法吗?

我的<MyNavigator>组件:

export class MyNavigator extends Component {
    constructor(props) {
        super(props);
        this._renderScene = this._renderScene.bind(this);
    }
    _renderScene(route, navigator) {
        var Component = route.component;
        return (
            <Component {...route.props} navigator={navigator} route={route} />
        );
    }
  render() {
    const routes = [
        {component: FooListScreen, index: 0},
        {component: NewFooScreen, index: 1}
    ];

    return (
        <Navigator
        initialRoute={routes[0]}
        initialRouteStack={routes}
        renderScene={this._renderScene}
        navigationBar={
              <Navigator.NavigationBar
              routeMapper={{
         LeftButton: (route, navigator, index, navState) =>
          { 
            if(route.index === 0){
                return null
            } else {
                return (
              <TouchableHighlight onPress={() => navigator.pop()}>
              <Text>Back</Text>
              </TouchableHighlight>
              ); 
            }
          },
         RightButton: (route, navigator, index, navState) =>
           {
           if (route.index === 0){
            return (
              <TouchableHighlight onPress={() => navigator.push({
                component: NewFooScreen
              })}>
              <Text>New Foo!</Text>
              </TouchableHighlight>
            )
           } else {
            return null;
           } 
         },
         Title: (route, navigator, index, navState) =>
           { return null; },
       }} />
    } /> );
  }
}

<NewFooScreen>组件中:

    _onPressButton(){
        realm.write(()=> {
          //Create a new Foo and save to realm db
            realm.create('Foo', {
                    name: this.state.fooName
            });

    //Somehow call _refreshData() in the FooList Component?? 
    //Through the Navigator? Using didFocus?

         this.props.navigator.pop();
    }

0 个答案:

没有答案