【发布时间】:2021-11-06 22:41:30
【问题描述】:
这是我的代码:
import React, { useState, useEffect } from "react";
import axios from 'axios';
function App() {
const [arrName, setName] = useState();
useEffect(() => {
axios.get('URL')
.then( response => {
// console.log( response.data )
setName( response.data )
});
}, [])
const foo = () => {
console.log(arrName.data[0].data[0]._id)
// following two console statements need not to be in the code. I am putting them only to show the structure of API
console.log(arrName)
console.log(arrName.data)
}
return(
<div>
Hi, I'm the component
<button onClick={foo}> console </button>
</div>
)
}
export default App;
控制台响应截图
我想简化以下陈述。这样我就可以轻松地迭代 API 并从 API 打印任何内容。但是,我在这里只打印一个 id。
console.log(arrName.data[0].data[0]._id)
以下命令会破坏代码
<div>
arrName.data[0].data.map((item) => <li>{item._id}</li> ) }
</div>
请帮助我对我的代码进行哪些更改。
【问题讨论】:
-
您想如何打印?我的意思是最终的预期结果?
-
想要迭代它类似于 arrayName.map(itr =>
- itr._id
) -
请检查我的答案,看看它是否符合您的需求。
标签: reactjs axios react-hooks use-effect use-state