[英]Objects are not valid as a React child when trying to map antd Select options
我試圖向我的 api 詢問 id 列表並將它們顯示在 antd 的Select
組件中。
<Select style={{ width: "100%" }}>
{myApi.getIds().then((result) => result.map((value) => {
return <Select.Option value={value}>{value}</Select.Option>
}))}
</Select>
value
是字符串。
getIds
返回Promise<string[]>
這會返回一個錯誤Objects are not valid as a React child (found: [object Promise]).
但該value
只是一個帶有 id 的字符串。 我在這里想念什么?
編輯:不知道它是否會幫助任何人,但我的解決方案,基於接受的答案是:
const [ids, setIds] = useState<string[]>(null);
useEffect(() => {
//some code
if (!ids) {
myApi.getIds().then((result) => setIds(result));
}
// some code
return () => { };
}, [ids]);
// some more code
return (
<>
//render other elements
<Select style={{ width: "100%" }}>
{ids?.map((value) => {
return <Select.Option value={value}>{value}</Select.Option>
})}
</Select>
//render other elements
</>
);
它不是在抱怨value
,而是在抱怨then
的返回值。
<Select style={{ width: "100%" }}>
{myApi.getIds().then((result) => result.map((value) => {
// −^^^^^^^^^^^^^^^^^^^^
return <Select.Option value={value}>{value}</Select.Option>
}))}
</Select>
then
的返回值為 promise。
您無法呈現像這樣調用getIds
的結果。 相反,您需要:
在父組件中執行getIds
並讓該組件將結果(當它可用時)作為道具傳遞給該組件,
或者
讓此組件執行getIds
並在useEffect
回調(帶掛鈎的功能組件)或componentDidMount
( class
組件)中等待結果,將結果保存在 state 中,並在渲染時使用 Z9ED39E2EA931586B3EZEF87。 當組件還沒有信息時,它必須處理渲染。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.