【发布时间】:2021-09-04 21:54:20
【问题描述】:
所以我有一个对象,它有一个嵌套的对象列表,即“贷款”
{
"cid": 1,
"fname": "test fnamne",
"mname": "test mname",
"lname": "test lane",
"address": "test address",
"gender": "Male",
"sourceOfFund": "work",
"coMaker": null,
"contactNumber": "09382853287432",
"loans": [
{
"id": 1,
"location": 1,
"area": 100,
"pricePerArea": 4000,
"interest": 16,
"term": 24,
"downPayment": 20000,
"dppurpose": 1
}
]
}
如何在 react 中使用 jsx 代码有效地映射贷款对象? 我目前有这个代码:
function DataFetching() {
const [customer, setCustomer] = useState({})
const [id, setId] = useState(1)
const [idFromButtonClick, setIdFromButtonClick] = useState(1)
const handleClick = () => {
setIdFromButtonClick(id)
}
useEffect(() => {
axios
.post(`http://localhost:9090/api/customer/getCustomerByCid`,{cid:idFromButtonClick})
.then(res => {
console.log(res)
setCustomer(res.data)
})
.catch(err => {
console.log(err)
})
}, [idFromButtonClick])
return (
<div>
<input type='text' value={id} onChange={e => setId(e.target.value)}/>
<button type='button' onClick={handleClick}>Fetch Post</button> <br></br><br></br>
{ customer.loans.map(item => (<li key={item.id}>{item.area}</li>))}
</div>
)
}
这给了我一个错误“无法读取未定义的属性'map'” 任何帮助将不胜感激。
【问题讨论】:
-
试试这个方法 -->>
{ (customer?.loans || []).map(item => (<li key={item.id}>{item.area}</li>))}
标签: reactjs react-hooks jsx use-state