我从服务器接收数据作为json数据,但无法在浏览器中显示它,因为
“对象无效,不能作为React子对象(找到:带有键{_id,Id,Name,Age}的对象)。如果要渲染子对象的集合,请使用数组代替,或使用来自React插件。在学生中检查render方法”
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;
该错误表明这this.state.post.data是一个对象,因此您需要在渲染之前将其转换为字符串。用JSON.stringify()
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> ); } }