React native React Native:API第二次未调用(fetch/axios)
我正在使用fetch方法创建react本机应用程序,以从API获取数据,但当我构建appremove并安装新应用程序时,它正在调用API,但在第二次调用时它没有。 我也有一些用途React native React Native:API第二次未调用(fetch/axios),react-native,react-native-router-flux,React Native,React Native Router Flux,我正在使用fetch方法创建react本机应用程序,以从API获取数据,但当我构建appremove并安装新应用程序时,它正在调用API,但在第二次调用时它没有。 我也有一些用途 componentDidMount, componentWillMount 但对我来说不是工作。以下是我的代码: export default test extends Component{ _isMounted = false; constructor(props){ super(props); this.
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 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)
})
}
}
如果您需要在方法中访问它,那么idea组件只调用一次。还要注意的是,componentWillMount已被弃用,您不应该使用它!谢谢但是,当我进入该屏幕时,如何调用API?您使用的是哪种导航器?react native router Flux您使用的是堆栈导航器吗?if-then stack navigator使用类似缓存的机制,在预先访问的情况下将屏幕加载到堆栈中。或者你可以在这里发布完整的代码。