【问题标题】:React Native: API is not calling on 2nd time(fetch/axios)React Native:API 没有第二次调用(fetch/axios)
【发布时间】:2019-03-02 15:26:05
【问题描述】:

我正在使用 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
}

}

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

【问题讨论】:

  • componentDidMount 只被调用一次。另请注意,componentWillMount 已弃用,您不应使用它。
  • 哦!谢谢。但是,当我进入该屏幕时,如何调用 API?
  • 您使用的是哪个导航器?
  • react-native-router-flux
  • 您使用的是堆栈导航器吗? if then stack navigator 使用类似缓存的机制,如果屏幕被预先访问,则将其加载到堆栈中。或者你可以在这里发布完整的代码。

标签: react-native react-native-router-flux


【解决方案1】:

我会使用 react-native-router-flux 查看您场景中的 onEnter 钩子。

这样的事情应该可以工作:

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是个思路)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多