![](/img/trans.png)
[英]Objects are not valid as a React child (found: [object Promise]) in react render
[英]Can't render Objects inside JSX. Throwing error Objects are not valid as a React child (found: [object Promise])
我有一個基於類的 React 組件。 這是一個子組件,state 來自另一個父組件。 這是 JSX,它位於 map function 內。 在 map function 里面,有一個很大的 JSX 代碼,但我只放了相關部分。
{platformsList.map((item, index) => (
{item.platform_id ? (
<div>
{this.getSelectedProfiles(item.platform_id)}
</div>)) : ''}
對應的function寫在render方法上面。 這里的響應是 Object:
getSelectedProfiles = async(id) => {
const token = Cookie.get('user-token');
const headers = {
'Content-Type': 'application/json',
authorization: token,
};
// Axios request
let response = await axios.get(`http://localhost:9999/profiles/${id}`, { headers: headers });
console.log(response);
return 'value';
}
它顯示的錯誤消息是:錯誤:對象作為 React 子項無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。
因為,這是一個子組件,我不想存儲在 React 的 state 中。 我想執行這個組件。 有沒有辦法不將其存儲在 state 中。 我是 React 新手,不知道我在哪里做錯了。
getSelectedProfiles
是異步的,並返回您嘗試在組件中呈現的 promise。 這就是 react 拋出錯誤的原因。
不得在渲染 function 中調用 API。 您可以將此邏輯分離到另一個組件中,並根據您編寫的組件類型在 componentDidMount 生命周期/useEffect 掛鈎中調用 API
{platformsList.map((item, index) => item.platform_id ? <Child key={index} id={item.platform_id} /> : null
}
...
const Child = ({id}) => {
const [data, setData] = useState({});
const [isLoading, setLoading] = useState(true);
useEffect(() => {
const getSelectedProfiles = async(id) => {
setLoading(true);
const token = Cookie.get('user-token');
const headers = {
'Content-Type': 'application/json',
authorization: token,
};
// Axios request
let response = await axios.get(`http://localhost:9999/profiles/${id}`, { headers: headers });
console.log(response);
setData({value: value}); // set the appropriate data here
setLoading(false);
}
}, [id]);
if(isLoading) return <div>Loading...</div>
// return the appropriate content here from data. Do not render the object as it is
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.