簡體   English   中英

如何在 react.js 的單個對象中添加屬性?

[英]how to add a property in a single object in react.js?

我想在類對象中添加一個元素

{ "userId": 1, "id": 1, "title": "sunt aut", "body": "quia et suscipit" }

我想要像下面

{ "userId": 1, "id": 1, "title": "sunt aut", "body": "quia et suscipit" "image": "image-name.jpg" }

let {postDetail} = useParams();
const url = `https://jsonplaceholder.typicode.com/posts/${postDetail}`;
const [details, setDetails] = useState([]);
useEffect(()=>{
    fetch(url)
    .then(res => res.json())
    .then(data => {
        setDetails(data => [...data, {"image":`${data.id}`}]);
    })
    
},[]);

我相信你覆蓋了data的價值。 看看這個:

useEffect(() => {
   fetch(url)
      .then(res => res.json())
      .then(res => {   // Rename this from "data" to "res" (or anything you like)
         setDetails([...details, { image: res.id }]);
      });
}, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM