【发布时间】: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