【问题标题】:React Native API FetchReact Native API 获取
【发布时间】:2016-10-26 10:06:52
【问题描述】:

我正在尝试使用以下代码 sn-p 在本机反应中使用 fetch api。每当我尝试 console.log API 数据数组时,它总是出现“未定义”?!?!

Home.JS

import api from '../components/api';

class Home extends Component {

constructor(props){
 super(props);
 this.state = {
  profile: []
 }
}

componentWillMount(){
 api.getProfile().then((res) => {
  this.setState({
    profile: res.profile
   })
 });
}
render() {
 console.log("Profile: ", this.state.profile); // Console Out API Data
 return (
  <View style={styles.container}>
    <Text style={styles.welcome}></Text>
  </View>
  );
 }
};

API.JS

var api = {
 getProfile(){
    var url = 'https://api.lootbox.eu/xbl/us/Food%20Market/profile';
    return fetch(url).then((res) => res.json());
 }
};

module.exports = api;

【问题讨论】:

  • 尝试使用console.log res.data 而不是res.profile
  • 这个解决方案不走运:/

标签: javascript react-native fetch react-native-android


【解决方案1】:

这里的问题是使用componentWillMount 来获取数据。检查这些part 的文档:

componentWillMount() 在安装发生之前立即调用。它 在 render() 之前调用,因此在此方法中设置状态将 不会触发重新渲染。避免引入任何副作用或 此方法中的订阅。

这是在服务器渲染上调用的唯一生命周期钩子。一般来说, 我们建议改用 constructor()。

基本上,您需要使用componentDidMount。见here:

componentDidMount() 在组件被调用后立即调用 安装。需要 DOM 节点的初始化应该放在这里。如果你 需要从远程端点加载数据,这是一个很好的地方 实例化网络请求。在此方法中设置状态将 触发重新渲染。

顺便说一句,如果你这样做(直接进入组件),你需要确保处理响应到来并且组件已被卸载的情况。在这种情况下,您可以在卸载组件之前使用componentWillUnmount 取消任何请求。

【讨论】:

    【解决方案2】:

    我希望为时不晚,我遇到了同样的问题,偶然发现了你的问题。 您所要做的就是将res.profile 更改为res。我确定您的 json 响应中没有 profile 数据

     componentWillMount(){
          api.getProfile().then((res) => {
          this.setState({
           profile: res
        })
      });
    }
    

    我希望这对有需要的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2021-12-10
      • 2020-05-08
      • 2018-06-12
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多