简体   繁体   English

“对象作为 React 子项无效”

[英]“Objects are not valid as a React child”

    import React,{useEffect,useState} from "react"
    import axios from "axios"
    import './App.css';
    import Move from "./Move";
    
    
    function App() {
      const [data,setData] = useState([]);
      useEffect(()=> {
       axios.get("https://api.themoviedb.org/3/movie/popular?api_key={apikey}&language=en-US&page=1").then((res)=> {
        setData(res.data.results)
       
       
       })
      },[])
    
      return (
       <div>
        
        <div className="App">
    <input placeholder="enter something" />
    <label></label>
        </div>
        {
        data.map(function(movie){
          console.log(movie)
        const title = movie.title
        const id = movie.id
         
        return <Move key={id} title={title}  />
    })}
        </div>
      );
    
    
    
    
      }
    
    
    
    
    
    export default App;
Component Im Trying To Render
import React from 'react'

const Move = (title) => {
  return (
      <div>
    <div>Move</div>
    <h1>{title}</h1>

</div>
  )
}

export default Move

im trying get access properties of the object for example title but im getting the error “Objects are not valid as a React child”我正在尝试获取 object 的访问属性,例如标题,但我收到错误“对象作为 React 子项无效”

the object is: object 是:

{
    "adult": false,
    "backdrop_path": "/iQFcwSGbZXMkeyKrxbPnwnRo5fl.jpg",
    "genre_ids": [
        28,
        12,
        878
    ],
    "id": 634649,
    "original_language": "en",
    "original_title": "Spider-Man: No Way Home",
    "overview": "Peter Parker is unmasked and no longer able to separate his normal life from the high-stakes of being a super-hero. When he asks for help from Doctor Strange the stakes become even more dangerous, forcing him to discover what it truly means to be Spider-Man.",
    "popularity": 8450.164,
    "poster_path": "/1g0dhYtq4irTY1GPXvft6k4YLjm.jpg",
    "release_date": "2021-12-15",
    "title": "Spider-Man: No Way Home",
    "video": false,
    "vote_average": 8.4,
    "vote_count": 8021
}

not sure what the problem is不确定是什么问题

 const Move = (title) => { return ( <div> <div>Move</div> <h1>{title}</h1> </div> ); };

In this code, title is the entire props object. You need to access just the title property on that object:在此代码中, title是整个道具 object。您只需要访问 object 上的 title 属性:

const Move = (props) => {
  return (
    <div>
      <div>Move</div>
      <h1>{props.title}</h1>
    </div>
  );
};

Or with destructuring:或者解构:

const Move = ({ title }) => {
  return (
    <div>
      <div>Move</div>
      <h1>{title}</h1>
    </div>
  );
};

import React from 'react'

const Move = (prop) => {
  return (
      <div>
    <div>Move</div>
    <h1>{prop.title}</h1>

</div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM