尝试映射 antd 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 returns Promise<string[]>

这 returns 一个错误 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 的 return 值。

<Select style={{ width: "100%" }}> 
    {myApi.getIds().then((result) => result.map((value) => {
// −^^^^^^^^^^^^^^^^^^^^
        return <Select.Option value={value}>{value}</Select.Option>
    }))}                                               
</Select>

then 的 return 价值是一个承诺。

您不能像那样呈现调用 getIds 的结果。相反,您需要:

  1. 在父组件中执行 getIds 并让该组件将结果(当它可用时)作为 prop 传递给该组件,

  2. 让此组件执行 getIds 并在 useEffect 回调(功能组件 w/hooks)或 componentDidMountclass component), 将结果保存在状态中,并在渲染时使用该状态。当组件还没有信息时,它必须处理渲染。