React Native:API第二次没有调用(fetch / axios)

问题描述 投票:0回答:1

我正在使用fetch方法创建react-native应用程序来从API获取数据,但是当我构建应用程序(删除并安装新应用程序)时,它正在调用API调用但是第二次它不是。我也用过

componentDidMount, componentWillMount

但不适合我。以下是我的代码:

export default test extends Component{
_isMounted = false;
constructor(props){
  super(props);
  this.state = {
      showList:[]
 }
}
componentDidMount() {
    let currentComponent = this;
     currentComponent._isMounted = true;
    fetch(API_URL, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    }).then((response) => { return response.json()})
    .then((responseJson) => {
        console.warn("responseJson: ", responseJson);
        if(currentComponent._isMounted){
         currentComponent.setState({showList: responseJson.data});
        }

    })
    .catch((error) => {
      console.error(error);
    }); 

}
componentWillUnmount(){
    this._isMounted = false
}

}

我在这里添加了完整的代码。这只是第一次调用,之后它只能从缓存中获取(我认为)。请帮助我。谢谢

react-native react-native-router-flux
1个回答
1
投票

我会用onEnter调查你场景中的react-native-router-flux钩子。

这样的事情应该有效:

class Test extends Component {
  static onEnter() {
    fetch(API_URL, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    }).then((response) => { return response.json()})
    .then((responseJson) => {
        console.warn("responseJson: ", responseJson)
        if (currentComponent._isMounted) {
         currentComponent.setState({ showList: responseJson.data })
        }

    })
    .catch((error) => {
      console.error(error)
    })
  }
}

(如果你需要在方法中访问thishere是个主意)

© www.soinside.com 2019 - 2024. All rights reserved.