API正常工作,但我无法让axios写入从API返回的数据

问题描述 投票:-1回答:1

我通过浏览器(https://localhost:41216/api/articles)连接到Axios时看起来像这样的API:

[{"id":1,"name":"Detection of solar neutron events and their theoretical approach","groupById":2,"groupBy":null},
{"id":2,"name":"Dark energy and modified scale covariant theory of gravitation","groupById":2,"groupBy":null},
{"id":3,"name":"United theory of planet formation (i): Tandem regime","groupById":2,"groupBy":null}]

我有工作,但它像这样硬编码:

import React from "react";

const OptionList = () => {

    return (
        <>
            <option value='Article' label='Select an article' />
            <option value='1' label='Detection of solar neutron events and their theoretical approach' />
            <option value='2' label='Dark energy and modified scale covariant theory of gravitation' />
            <option value='3' label='United theory of planet formation (i): Tandem regime' />               
        </>
    )
}

export default OptionList;  

但是我想使用API​​,所以我开始对此进行编码:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const OptionList = () => {

    const [data, setData] = useState('');

    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(
                'https://localhost:41216/api/articles',
            );
            setData(result.data);
        };
        fetchData();
    }, []);

    return (
        <>
            {data.map(item => (
                <option value={item.id} label={item.name} />
            ))}
        </>

    );
}
export default OptionList;

但是我仍然收到错误提示

TypeError: data.map is not a function

我知道API可以正常工作,因为我在浏览器中访问了URL,因此获得了返回的数据,就像上面的示例一样。

reactjs axios
1个回答
0
投票

    const [data, setData] = useState('');

data的默认值初始化为空字符串。

简单来说,

    const [ data, setData ] = useState([]);

通过将数据初始化为空数组以具有.map方法来解决此问题。

我也会

    function renderOptions() {
        if(data.length <= 0) {
            return <Loader />
        }
        return data.map(item => (
            <option value={item.id} label={item.name} />
        ))
    }

    return (
        <>
            {renderOptions()}
        </>

    );

[data没有要映射和生成<option>的地方,这会显示加载程序屏幕。

© www.soinside.com 2019 - 2024. All rights reserved.