【问题标题】:Didnt Get the Response Json From Post Method React Native没有从 Post 方法 React Native 获得响应 Json
【发布时间】:2018-03-08 04:00:02
【问题描述】:

我试图从我的 web api 获取数据,请求方法是 Post,post 方法的主体来自我从登录用户那里获得的 AsyncStorage。之后 resPonseJson 被保存到我的状态数据源中,之后我使用 flatlist 来显示数据。但是数据没有显示出来,当我尝试从 Get 方法获取数据时,数据显示在我的平面列表中,但是当我尝试使用 Post 方法时

componentDidMount(){
  let FirstName = this.state.FirstName;
return fetch('http:example.com/api/select', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
   FirstName: FirstName,
 }),

})
.then((response) => response.json())  
.then((responseJson) => {

  this.setState({
    isLoading: false,
    dataSource: responseJson,
  }, function(){

  });

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

 render() {


    return(
      <View style={{flex: 1, paddingTop:20}}>
       <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.LastName}, {item.Gender}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

所以这里的问题是什么,你可以看到我的 web api 很好,我检查了我的 FirstName 状态是否也有来自 AsyncStorage 的数据,没有错误消息,这里有什么建议吗?谢谢

更新 我想我知道这里发生了什么,当我尝试在 body 中硬编码 FirstName 时效果很好,但是当我将 body 更改为它不起作用时,这里有任何建议

【问题讨论】:

    标签: javascript reactjs react-native fetch


    【解决方案1】:

    链接响应应该看起来更像这样,特别是 response.json 部分。然后你应该在 console.log 中得到一个对象。

    .then(response => response.json())
    .then(response => {
    
    console.log(response);  
    

    【讨论】:

    • 所以 dataSpurce setState ,会像这样 dataSource : console.log(response); ?
    • 使用 .then(response => response.json()) 然后就可以了。
    • 如果你使用花括号进行回调,你需要返回 response.json()。简化形式 response => response.json() 有一个隐式的 return 语句。
    • 嗨,对不起,但看起来你只是从这个答案 stackoverflow.com/questions/33237200/… 复制,
    • 嗨@Theodorus Agum Gumilang,我正在使用它,因为它对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多