Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

reactjs - Getting "Error: Objects are not valid as a React child when rendering object values

I am trying to render values from data object in an array but I have got these error messages

Error: Objects are not valid as a React child (found: object with keys {id, course_code, course_name, slug, course_fee, duration, start_date, end_date,}

I don't really know where am getting it wrong. Here is the API object response.

{
  "success": true,
  "message": "Course Retrieved Successfully.",
  "data": {
    "id": 1,
    "course_code": "null",
    "course_name": "Greatness",
    "slug": "greatness",
    "course_fee": 10,
    "duration": "10hours",
    "start_date": "2000-09-08",
    "end_date": "2000-09-08",
  }
}

My code below

const [coursedetails, setCourseDetails] = useState([])
const [status,setStatus] = useState('init');

const init =()=>{
  setStatus('loading')

  return axios.get('http://example.com/api/courses').then(response => {
      setCourseDetails(response.data);
      setStatus('success')
    }).catch(error =>{
      console.log('error',error)
      setStatus('error')
    })
}

useEffect(()=>{
  init()
},[])


return(
  <div>

  {coursedetails.data && coursedetails.data.course_name ? coursedetails.data : ''}
  <div>
)
question from:https://stackoverflow.com/questions/65877656/getting-error-objects-are-not-valid-as-a-react-child-when-rendering-object-val

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your closing tag is incorrect. It should be </div> instead of <div>

<div>

{coursedetails.data && coursedetails.data.course_name ? coursedetails.data : ''}
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...