繁体   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