【问题标题】:React Native - Navigate after an async actionReact Native - 在异步操作后导航
【发布时间】:2016-07-14 06:39:41
【问题描述】:

我正在使用 React Native 和 Redux 开发一个移动应用程序,但我遇到了一个软件设计问题。 如果该操作成功,我想调用 REST API(异步操作)进行登录并导航到主视图。 我正在使用 redux 和 thunk,所以我已经实现了异步操作,所以我的主要疑问是:我应该将导航到主视图的逻辑放在哪里?

我可以直接从操作访问导航器对象并在那里执行导航吗? 我应该在登录组件中这样做吗? (因为我已经这样做了 - 检查下面的代码)。

componentWillReceiveProps(nextProps){
    if(nextProps.errorLoginMsg){
        Alert.alert("Login Failed", nextProps.errorLoginMsg);
    }
    else if(!nextProps.user.isNull()){
      this.props.navigator.replace({name: 'main'});
    }
  }

我不确定组件中是否包含该逻辑。似乎不是一个好习惯。有没有其他方法可以做到这一点?

谢谢

【问题讨论】:

    标签: ios reactjs react-native redux react-router-redux


    【解决方案1】:

    这是使用当前 Navigator API 进行本机反应时最困难的问题之一。我建议拥有一个包含当前路线的路线商店,并让包含导航器的组件连接到该商店并在componentWillReceiveProps 上触发导航。

    【讨论】:

      【解决方案2】:

      这是我的代码:

                      const resetAction = NavigationActions.reset( {
                          index  : 0,
                          actions: [
                              NavigationActions.navigate( { routeName: 'Home' } )
                          ]
                      } );
      
                      this.props.requestDeleteEvent( {
                          id: eventID
                      } ).then( () => {
                          this.props.navigation.dispatch( resetAction );
                      } );
      

      在函数 requestDeleteEvent 内部:

      export function requestDeleteEvent(requestData) {
          const id = requestData.id;
      
          return (dispatch, getState) => {
              return fetch(Config.event + id, {
                  method: 'DELETE',
                  headers: {
                      'Content-Type': 'application/json; charset=UTF-8',
                  },
              })
                  .then((response) => getResponseJson(response))
                  .then((responseJson) => {
                          if (responseJson.isSuccess) {
                              return dispatch(deleteEvent(id));
                          } 
                          else {
                              return dispatch(triggerToast({type: 'alert', content: ERROR}));
                          }
                      }
                  );
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 2020-07-18
        • 1970-01-01
        • 1970-01-01
        • 2017-10-30
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多