How to navigate in mobx store using react navigation?

后端 未结 3 1513
甜味超标
甜味超标 2021-01-16 11:36

I can use this.props.navigation from screen component to navigate. How should I do the similar in mobx store file? Or should I perform navigation in store?

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 12:02

    You can keep all your states including navigation state in mobx store.

    For example:

    // sourced and modified from https://github.com/react-community/react-navigation/issues/34#issuecomment-281651328
    
    class NavigationStore {
      @observable headerTitle = "Index"
      @observable.ref navigationState = {
        index: 0,
        routes: [
          { key: "Index", routeName: "Index" },
        ],
      }
    
      // NOTE: the second param, is to avoid stacking and reset the nav state
      @action dispatch = (action, stackNavState = true) => {
        const previousNavState = stackNavState ? this.navigationState : null;
        return this.navigationState = AppNavigator
            .router
            .getStateForAction(action, previousNavState);
      }
    }
    
    // NOTE: the top level component must be a reactive component
    @observer
    class App extends React.Component {
      constructor(props, context) {
        super(props, context)
        // initialize the navigation store
        this.store = new NavigationStore()
      }
    
      render() {
        // patch over the navigation property with the new dispatch and mobx observed state
        return (
           { /* left blank */ }
          })}/>
        )
      }
    };
    

    Then you can directly call the dispatch action of the store to navigate to a new screen.

提交回复
热议问题