![](/img/trans.png)
[英]How to update the value of a single property within a state object in 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.