[英]Map Axios data outside of render in React
I am trying to call.map() on data from Axios before passing it into the return statement.我试图在将 Axios 中的数据传递给 return 语句之前调用它。 The point of this is I want to use Material UI tables, and their pattern is to construct rows, then map the rows value in the return.重点是我要使用Material UI表,它们的模式是构造行,然后map返回行值。 I cannot figure out what I am doing wrong.我无法弄清楚我做错了什么。
useEffect(() => {
axios
.get (url, {
auth: {
username: username,
password: password
}
})
.then(response => setData (response.data.result));
}, [])
function createData(id) {
return {id}
}
const newArray = element => {
data.map ({
id: element.Id
})
return newArray
}
const rows = [
createData(newArray.id)
]
console.log(data) //returns the correct array
console.log(newArray.id) //returns undefined
console.log(rows) //returns id:undefined
return (
<div>
{rows.map(row => (
<TableCell component="th" scope="row">
{row.id}
</TableCell>
))}
</div>
)
}
Assuming response.data.result
(from your axios request) is an array of objects with an Id
property, for example:假设response.data.result
(来自您的 axios 请求)是具有Id
属性的对象数组,例如:
[
{ Id: 1, ... },
{ Id: 2, ... }
]
...then perhaps something like this will solve your problem: ...那么也许这样的事情会解决你的问题:
function Example(props) {
const [ rows, setRows ] = useState([])
useEffect(() => {
axios
.get(url, {
auth: {
username: username,
password: password
}
})
.then(response => {
// Assuming "response.data.result" is an array here
const data = response.data.result
const ids = data.map(element => {
return { id: element.Id }
})
setRows(ids)
});
}, [])
return (
<div>
{rows.map(row => (
<TableCell component="th" scope="row">
{row.id}
</TableCell>
))}
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.