有多個標題相同的問題,但由于某種原因,我的案例很簡單,但我無法解決。
我有一個提供此回應的 API:
{
"customer":{
"default_address":{
"address1":null,
"city":null,
"country":null,
"first_name":"Chaudhry",
"user_id":1234,
"last_name":"Talha",
"name":"Chaudhry Talha",
"phone":"12345667",
"province":null,
"zip":"12345"
}
}
}
我存盤在一個狀態:
...
const [customerInfo, setCustomerInfo] = useState({});
...
setCustomerInfo(response.customer.default_address)
...
我收到此錯誤:
物件作為反應組件無效。(找到:帶有鍵 {} 的物件)。如果您打算渲染一組子項,請改用陣列。
基于一個解決方案,我改為 useState:
const [customerInfo, setCustomerInfo] = useState([]);
錯誤:物件作為 React 子物件無效(發現:物件的鍵為 {user_id、first_name、last_name、address1、城市、省、國家/地區、郵編、電話、姓名、國家/地區、默認值})。如果您打算渲染一組子項,請改用陣列。
它也給了我這個錯誤:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
For the above error, I'm basically doing this in my code:
useEffect(() => {
myservice.getUserProfile("USER_ID").then((response) => {
setCustomerInfo(response.customer.default_address)
...
}, [])
I've also tried putting it as null:
const [customerInfo, setCustomerInfo] = useState(null);
but got the same error i.e. Objects are not valid as a React child (found: object with keys...
So, how do I parse it?
uj5u.com熱心網友回復:
我剛剛在我的本地空間中嘗試了你的代碼,
我真的看不出你的代碼有問題,我只是將你在狀態中的宣告型別更改為 null,這樣他們就可以獲取你提供給他們的任何型別的資料,所以試試這個:
const [customerInfo, setCustomerInfo] = useState(null);
const [shippingAddress, setShippingAddress] = useState(null);
uj5u.com熱心網友回復:
我假設您正在嘗試映射“shippingAddress”?
保持
const [customerInfo, setCustomerInfo] = useState([]);
進而
{shippingAddress.map((value, index) => {
return(
<p key={index}>{value.name}</p> //use this to adjust what you want to display
)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338460.html
