简体   繁体   English

如何在 ReactJS 中获取 ajax 数据

[英]How to get ajax data in ReactJS

I am building ontop of a ReactJS embedable web ui script as I am new to ReactJS.我正在构建 ReactJS 可嵌入 web ui 脚本,因为我是 ReactJS 的新手。 Here I am trying to pull data from my server and trying to display in the web ui.在这里,我试图从我的服务器中提取数据并尝试在 web ui 中显示。 The problem I am facing is with the data that is coming from server as I am unable to parse it.我面临的问题是来自服务器的数据,因为我无法解析它。 Please find the data format below:请在下面找到数据格式:

0: Object { name: "{\"draw\":0,\"recordsTotal\":8,\"recordsFiltered\":8,\"data\":[{\"first_name\":\"John\",\"last_name\":\"taylor\"},
{\"first_name\":\"John1\",\"last_name\":\"taylor1\"}]}" }
​
1: Object { school: "{\"draw\":0,\"recordsTotal\":0,\"recordsFiltered\":0,\"data\":
[{\"name\":\"school1\",\"location\":\"location1\"},
{\"name\":\"school2\",\"location\":\"location2\"}]}" }

PS: I cannot change my server data format. PS:我无法更改我的服务器数据格式。

Model code (model.ts) Model 代码(model.ts)

export interface NameModel {
    name: object;
}

Form code (form.tsx)表单代码 (form.tsx)

const Name = () => {
    const service = useContext(ServiceContext);
    const [name, setName] = useState<NameModel[] | undefined>(undefined);
    const [visible, setVisible] = useState(0);
    const [statusText, setStatusText] = useState('');

    const loaders = [useTimeout(() => !name && setStatusText('Loading...'), 500)];

    useEffect(() => {
        service?.getName()
            .then(setName)
            .catch(() => setStatusText('Failed to load, try again later.'))
            .then(() => loaders.forEach((c) => c()));
    }, [service]);

    return (
        <div>
            {
                !name
                    ? statusText
                    : <Fragment>
                        <ul className={style.root}>
                            {
                                name.map((q, i) => (
                                {q}
                                    ))
                            }
                        </ul>
                    </Fragment>
            }
        </div>
    );
};

The above code produces: Uncaught (in promise) TypeError: name.map is not a function上面的代码产生: Uncaught (in promise) TypeError: name.map is not a function

How do I display the first_name and last_name from the first object that is sent from my server?如何显示从我的服务器发送的第一个 object 的名字和姓氏?

Thanks谢谢

Your issue is that name can be undefined by default, causing the name.map((q... part of the code to error because undefined doesn't have a map function.您的问题是name默认情况下可能undefined ,导致name.map((q...部分代码出错,因为undefined没有map function。

You can fix this by changing to a more sensible default of empty array:您可以通过更改为更合理的默认空数组来解决此问题:

const [name, setName] = useState<NameModel[]>([]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM