用react解析json格式的字符串到object



我对反应完全陌生。我做了一些简单的应用程序,从后端接收字符串。

字符串看起来像

"[{"name":"David", "age":"20"},{"name":"Michael", "age":"10"}]"

现在我设法使它成为一个字符串,并渲染它的网站,我找不到正确的方法使这个字符串成为一个对象,并访问它的值来创建一个表,将显示不同的对象的详细信息。

i have found a functionJSON.parse(obj)

但是我想我用错了。

我正在添加我的代码从App.js, atm渲染在网站上。

function App() {
const [items, setItems] = useState([])
// Using useEffect for single rendering
useEffect(() => {
// Using fetch to fetch the api from
// flask server it will be redirected to proxy
fetch("/data")
.then((res) => res.json()
.then((data) => setItems(data))
);
}, []);
return (
<div className="App">
{items.map(item => {
return <pre>{JSON.stringify(item)}</pre>
})}
</div>
);
}
export default App;

您只需要这样做:

return(
<table>
<thead>
<th>name</th>
<th>age</th>
</thead>
<tbody>
{items.map((item: any) => {
return (
<tr>
<td>{item.name}</td>
<td>{item.age}</td>
</tr>
)
})}
</tbody>
</table>
)

res.json()已经将您的数据转换为JSON,因此您不需要做任何额外的工作。你可以开始使用你的数据了。

在你的.map()方法item是对象,你需要使用和访问它的属性通过简单地做item.propertyName,你可以看到在我分享的代码。

相关内容

最新更新