首页 > 解决方案 > 如何在反应中处理调度后导航

问题描述

我遇到了麻烦,因为在将数据放入商店react-navigation后,我找不到导航到屏幕的方法。redux我尝试做很多事情,但无济于事,问题一直存在。问题是redux在屏幕弹出之前商店的调度速度不够快,然后屏幕出现错误,因为 json 文件的某些部分不存在。我想知道在使用必要的 JSON 文件更新商店之前是否会暂停导航。

这是我的应用程序中出现问题的部分。

_onPress = () => {
    if (this.state.taxonA == "" || this.state.taxonB == "") {
      Alert.alert("One or more fields have been left empty.");
      return;
    }
    let url = V.sprintf(
      "http://timetree.igem.temple.edu/api/pairwise/%s/%s",
      this.state.taxonA,
      this.state.taxonB
    );
    const { fetchData } = this.props;
    fetchData(url);
    console.log("should have fetched");
    //while(this.props.response.isFetching == true){}
    this.props.navigation.navigate("Picker");
  };

这是fetchData功能

export const fetchData = url => {
  console.log("Should enter async dispatch");
  return async dispatch => {
    dispatch(fetchingRequest());
    try{
      let response = await fetch(url);
      let json = await response.json();
      let dispatchChecker = dispatch(fetchingSuccess(json));
      console.log("DISPATCH", dispatchChecker);
      console.log("JSON",json);
      console.log(JSON.stringify(json, null, 2));
    }catch(error){
      console.log("ERROR",error);
      dispatch(fetchingFailure(error));
    }
  };
};

输出应该是从一个屏幕到另一个屏幕的过渡。但相反,应用程序将获得一个红色屏幕,cannot read property of 'found_taxon_a' of null其中包含以下语句:found_taxon_a 是获取的 JSON 文件中的一个对象。

标签: react-nativereact-navigation

解决方案


fetchData在导航到另一个屏幕之前等待完成:

fetchData(url)
  .then(() => this.props.navigation.navigate('Picker'))
  .catch(err => console.log('Do something'));

推荐阅读