[英]How do I render a list from Json data in express js, then render it using react and map()?
I had a question, and a problem when rendering Json data with react js.我有一个问题,在使用 react js 渲染 Json 数据时出现问题。 I Couldn't get react to map out the data.我无法从数据中对 map 做出反应。 Here is my code:这是我的代码:
My Json:我的 Json:
res.json({
list: [{id: 1, name: 'Caleb'}, {id: 2, name: 'Isaiah'}]
})
My React Code:我的反应代码:
import { useState, useEffect } from 'react'
function App() {
const [data, setData] = useState({})
useEffect(() => {
fetch("/home")
.then(res => res.json())
.then(data => setData(data))
}, [])
return (
<div>
{data.list.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}
export default App;
Its giving me this error, that it cant render it properly.它给了我这个错误,它不能正确渲染它。
I fixed it by first putting the Json data into a variable, then made sure that the variable wasn't undefined, then rendered it: Like this:我首先将 Json 数据放入一个变量中,然后确保该变量不是未定义的,然后渲染它:像这样:
import { useState, useEffect } from 'react'
function App() {
const [data, setData] = useState({})
useEffect(() => {
fetch("/home")
.then(res => res.json())
.then(data => setData(data))
}, [])
const new_data = data.list;
const renderAuth = () => {
if (new_data !== undefined) {
return (
<div>
{new_data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
} else {
console.log("sorry had problems")
}
}
return (
<div>
{renderAuth()}
</div>
);
}
export default App;
Then it worked like a charm.然后它就像一个魅力。 No problems at all.完全没有问题。
The simplest way to achieve your goal is to use conditional rendering (&&), you can put the JSON data in a variable, but it's not necessary.实现目标的最简单方法是使用条件渲染 (&&),您可以将 JSON 数据放在变量中,但这不是必需的。 Another improvement is to use the object id as the key and not the index.另一个改进是使用 object id 作为键而不是索引。
Here's an example of how to improve your code:以下是如何改进代码的示例:
import { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState({});
useEffect(() => {
fetch("/home")
.then(res => res.json())
.then(data => setData(data))
}, [])
return (
<div>
{data.list && (
data.list.map(function (d) {
return <li key={d.id}>{d.name}</li>;
})
)
</div>
);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.