not able to display json data sent from server

前端 未结 2 810
无人及你
无人及你 2021-01-26 00:29

I am receiving data from server as json data but not a able to display it on the browser i am getting error as

\" Objects are not valid as a React child

相关标签:
2条回答
  • 2021-01-26 01:04

    JSON.stringify() convert whole object into a string, instead of using this, u can render the specific property of object. In ur case data object contains 4 keys _id, Id, Name, Age, so render it like this:

    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>
        );
      }
    

    By this way you will have a better control on each element, u can apply different styling, formats etc.

    0 讨论(0)
  • 2021-01-26 01:06

    The error suggests that this.state.post.data is an object and hence you need to convert it to a string before rendering. Use JSON.stringify()

    Try

    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>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题