簡體   English   中英

嘗試 map 和 Select 選項時,對象作為 React 子項無效

[英]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的結果。 相反,您需要:

  1. 在父組件中執行getIds並讓該組件將結果(當它可用時)作為道具傳遞給該組件,

    或者

  2. 讓此組件執行getIds並在useEffect回調(帶掛鈎的功能組件)或componentDidMountclass組件)中等待結果,將結果保存在 state 中,並在渲染時使用 Z9ED39E2EA931586B3EZEF87。 當組件還沒有信息時,它必須處理渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM