【问题标题】:How to navigate in mobx store using react navigation?如何使用反应导航在 mobx 商店中导航?
【发布时间】:2018-04-11 06:22:29
【问题描述】:

我可以使用屏幕组件中的this.props.navigation 进行导航。我应该如何在 mobx 商店文件中做类似的事情?还是我应该在商店中进行导航?

我阅读了Navigating without the navigation prop 的文章,但它似乎只适用于屏幕组件,对吧?

有人说使用global 变量来存储this.props.navigation 引用并在任何地方使用它,但我不喜欢这个想法...

【问题讨论】:

    标签: react-native react-navigation mobx mobx-react


    【解决方案1】:

    是的:

    调用方法时将导航类转发到商店:

    // add nivagation parameter to store fucntion:
    this.props.store.handleSomething(data, this.props.navigation);
    

    或者您可以单例导航器(警告仅适用于其中一个):

    return <Navigator ref={(nav) => this.props.store.navigator = nav} />;
    

    渲染完成后,它将在 store 中设置 navigator 属性。

    但我建议将所有路由状态也存储在这样的路由存储中:https://github.com/alisd23/mobx-react-router。

    通过这种方式,您始终可以轻松访问导航状态,并且可以确保所有内容都能正确重新渲染。 (在组件中的渲染功能也取决于导航的变化!)

    【讨论】:

      【解决方案2】:

      您可以在 mobx 商店中保留所有状态,包括导航状态。

      例如:

      // 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 (
            <AppNavigator navigation={addNavigationHelpers({
              dispatch: this.store.dispatch,
              state: this.store.navigationState,
              addListener: () => { /* left blank */ }
            })}/>
          )
        }
      };
      

      然后就可以直接调用store的dispatchaction来导航到新的界面了。

      【讨论】:

        【解决方案3】:

        将此this.props.navigation 作为参数发送到商店。然后像在组件端使用一样使用。

        LoginStore.login(this.props.navigation)
        

        在登录商店中

        @action login = (navigation) => { navigation.navigate('Page');}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-03
          • 1970-01-01
          • 2014-06-04
          • 2020-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多