获取请求后返回React forloop



我对反应还很陌生。我已经用axios成功地发出了获取请求,现在我想循环通过res.data并显示它。

我的请求如下:


const [post, setPost] = React.useState(null)
React.useEffect(() => {
axios({
method: 'get',
url: 'http://localhost:8080/api/tests',
headers: headers
}).then((res) => {
setPost(res.data);
console.log(res.data)
})
.catch((err) => { console.log(err) })
}, []);

现在,在我的返回中,我想循环遍历res.data数组中的每个Object并显示名称。我尝试添加一个带花括号的javascript forloop,但没有成功。


for (var i = 0; i < post.length; i++) {
<p>{i.name}</<p>
}

有人能帮我如何获得每个对象并在return函数中渲染它吗?

您需要从循环中返回一些内容,因此应该使用map()检查以下链接https://reactjs.org/docs/lists-and-keys.html.所以你的代码应该是这样的:

假设您有以下组件:

const Component = () => {
// Initialize the data with the datatype in this case it would be an empty array
// otherwise you will have to check if the array exists before looping
const [post, setPost] = React.useState([])
React.useEffect(() => {
axios({
method: 'get',
url: 'http://localhost:8080/api/tests',
headers: headers
}).then((res) => {
setPost(res.data);
console.log(res.data)
})
.catch((err) => { console.log(err) })
}, []);

return (
<div className="App">
{post.map(i => <p>{i.name}</p>)}
</div>
);
}

现在,您应该为列表中返回的每个项添加一个唯一的键。不确定你的数据是什么样子的,所以如果每个数据中都有一个唯一的标识符,你应该将其添加为返回项的密钥。所以像{post.map(i => <p key={i.name}>{i.name}</p>)}。但是,如果名称值有重复项,则需要使用不同的唯一标识符。

您想要使用.map((方法。这允许您创建一个jsx元素的数组,然后在组件中返回该数组。

const Component = () => {
// Initialize the data with the datatype in this case it would be an empty array
// otherwise you will have to check if the array exists before looping
const [post, setPost] = React.useState([])

React.useEffect(() => {
axios({
method: 'get',
url: 'http://localhost:8080/api/tests',
headers: headers
}).then((res) => {
setPost(res.data);
console.log(res.data)
})
.catch((err) => { console.log(err) })
}, []);

const names = post.map(({name}, index) => <p key={index}>{name}</p>
// It's important when using .map to create jsx elements from an array,
// that you include a key prop that is unique. The index of each element 
// works great in most cases
return (
<div className="App">
// React knows to spread out an array of JSX elements.
{names}
</div>
);
}

最新更新