[英]how to add a property in a single object in react.js?
I want to add an element in the object-like我想在类对象中添加一个元素
{ "userId": 1, "id": 1, "title": "sunt aut", "body": "quia et suscipit" }
I want like below我想要像下面
{ "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}`}]);
})
},[]);
I believe that you override the value of data
.我相信你覆盖了data
的价值。 Take a look at this:看看这个:
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.