【问题标题】:Can't load option choices into SelectInput with fetch()无法使用 fetch() 将选项选项加载到 SelectInput 中
【发布时间】:2019-07-28 14:57:08
【问题描述】:

我正在推送从 REST API 获取但未定义的数据。如何以正确的方式获取这些数据?

我的 API 回复:

[{
"id": 1,
"positionName": "Accounting Assistant III"
}, {
"id": 2,
"positionName": "Web Developer III"
}, {
"id": 3,
"positionName": "Graphic Designer"}]

我在 React 中的代码:

const getPosistions = async () => {
    const response = await fetch('http://localhost:8080/api/positions/');
    const myJson = await response.json();
    return myJson;
}

var positionsChoices;
getPosistions().then(function (result) {
    positionsChoices = result;
});

const EmployeeCreate = props => (
    <Create {...props}>
        <SimpleForm>
            <SelectInput
                source="id"
                choices={positionsChoices}
                optionText="positionName"
                optionValue="id"
            />
        </SimpleForm>
    </Create>
);

【问题讨论】:

    标签: reactjs react-admin


    【解决方案1】:

    React 不会在可变变量更改时重新渲染,除非您明确设置 propstatecontext 的新值。对于这种情况,state 似乎最合适 - 请阅读 State and Lifecycle 了解更多信息。

    作为奖励,如果您想查看 React Hooks 的实际应用:

    import React, {useState, useEffect} from 'react';
    
    const getPosistions = async () => {
        const response = await fetch('http://localhost:8080/api/positions/');
        const myJson = await response.json();
        return myJson;
    }
    
    const EmployeeCreate = props => (
        const [positionsChoices, setPositionsChoices] = useState();
    
        useEffect(() => {
          getPosistions().then((result) => setPositionsChoices(result));
        }, []);
    
        <Create {...props}>
            <SimpleForm>
                <SelectInput
                    source="id"
                    choices={positionsChoices}
                    optionText="positionName"
                    optionValue="id"
                />
            </SimpleForm>
        </Create>
    );
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2015-05-16
      相关资源
      最近更新 更多