【问题标题】:not able to display json data sent from server无法显示从服务器发送的 json 数据
【发布时间】:2017-06-12 18:12:22
【问题描述】:

我从服务器接收数据作为 json 数据,但无法在浏览器上显示它我收到错误

" 对象作为 React 子对象无效(找到:带键的对象 {_id,ID,姓名,年龄})。如果你打算渲染一个集合 孩子,使用数组代替或使用包装对象 来自 React 附加组件的 createFragment(object)。检查渲染方法 在学生”

import React from 'react';
import axios from 'axios';

class Student extends React.Component{
  constructor(props){
    super(props);
    this.state={
      post:[]
    }
  };


componentDidMount(){
  axios.get('http://localhost:8080/student')
  .then(data => this.setState({post:data}));
    }


  render(){
    return(
<div className="pre">

<h1>{this.state.post.data}</h1>
</div>
    );
  }
}
export default Student;

【问题讨论】:

  • axios 返回包含数据属性的响应对象。使用data.data
  • 你能不能在 axios .then 函数中记录数据并将结果包含在帖子中

标签: json reactjs


【解决方案1】:

该错误表明this.state.post.data 是一个对象,因此您需要在渲染之前将其转换为字符串。使用JSON.stringify()

试试

class Student extends React.Component{
  constructor(props){
    super(props);
    this.state={
      post:[]
    }
  };


componentDidMount(){
  axios.get('http://localhost:8080/student')
  .then(data => this.setState({post:data}));
    }


  render(){
    return(
<div className="pre">

<h1>{JSON.stringify(this.state.post.data)}</h1>
</div>
    );
  }
}

【讨论】:

    【解决方案2】:

    JSON.stringify() 将整个object 转换为string,而不是使用它,你可以渲染object 的特定属性。在你的情况下,数据对象包含 4 个键 _id, Id, Name, Age,,所以像这样渲染它:

    render(){
        return(
           <div className="pre">
              <h1>
                  Name: {this.state.post.data.Name}
                  <br/>
                  Age: {this.state.post.data.Age}
                  <br/>
                  Id: {this.state.post.data.Id}
              </h1>
           </div>
        );
      }
    

    通过这种方式,您可以更好地控制每个元素,您可以应用不同的样式、格式等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多