[英]I have a json data and I wanted to know how I can access the values using fetch api?
我有一个 json 数据,我想知道如何使用 fetch api 访问这些值,以便我可以在屏幕上打印它。 来自 jsonplaceholder 的 json 数据 . 我要显示的页面
. 该页面的代码。
import React, { useEffect, useState } from 'react';
function More() {
const [item, setItem] = useState();
const queryParams = new URLSearchParams(window.location.search);
const id = queryParams.get("id");
const fetchData = () => {
fetch(`https://jsonplaceholder.typicode.com/todos?userId=1&&id=${id}`)
.then((response) => response.json())
.then((json) => {
console.log(json)
setItem(json)
// console.log(item)
});
};
useEffect(() => {
fetchData();
}, [1])
//const id = new URLSearchParams(search).id;
//console.log(id);
return (
<div>
<h1>more information about list</h1>
<h3>Todo id: </h3>
</div>
)
}
export default More;
请在您的代码中使用const queryParams
和const id
并删除const id = 1;
const App = () => { const [item, setItem] = React.useState({}); // const queryParams = new URLSearchParams(window.location.search); // const id = queryParams.get("id"); const id = 1; const fetchData = () => { fetch(`https://jsonplaceholder.typicode.com/todos?userId=1&id=${id}`).then((response) => response.json()).then((json) => setItem(json[0])); }; React.useEffect(() => { fetchData(); }, [id]) return ( <div> <h1>more information about list</h1> <h3>Todo id: {item.id}</h3> <p>User id: {item.userId}</p> <p>Title: {item.title}</p> <p>Completed: {item.completed + ""}</p> </div> ) } ReactDOM.render( <App/>, document.getElementById('root') );
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="root"></div>
你的代码完美。 请在您的代码中添加此代码。
<div>
<h1>more information about list</h1>
{item?.map((data, i) => (
<div>
<h3>Todo id: {data.id}</h3>
<h3>Todo id: {data.title}</h3>
</div>
))}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.