【问题标题】:JSON to Dropdown in React - response.data.map is not a functionJSON to Dropdown in React - response.data.map 不是函数
【发布时间】:2022-09-30 00:36:16
【问题描述】:

我正在关注代码:https://codesandbox.io/s/cranky-leaf-2hupv?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js

该示例在我的 React 项目中有效,但是当我尝试将其调整为数据库中的值时,出现错误:

Uncaught (in promise) TypeError: response.data.map is not a function

我的 JSON 很简单

categories: 
0:  
Id: \"22\"
Name:   \"Strategy\"
1:  
Id: \"19\"
Name:   \"Sports\"
2:  
Id: \"27\"
Name:   \"Branding\"

我已经修改了代码以适合我的 JSON,如下所示:

import React, { Component } from \'react\';
import axios from \'axios\';


export default class TestDropdown extends React.Component {
    constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.state = {
            display: \"\",
            titles: [],
            errorMsg: \'\'
        };
    }

    toggle() {
        this.setState(prevState => ({
            dropdownOpen: !prevState.dropdownOpen
        }));
    }

    componentDidMount = (e) => {
        axios.get(\"https://mysite/devapi/categories.php\").then((response) =>
            this.setState({
                titles: response.data.map(({ Name }) => Name), /*error*/
                display:
                    response.data[Math.floor(Math.random() * response.data.length)].title
            })
        );
    };

    render() {
        const { display, titles } = this.state;
        return (
            <div className=\"container\">
                <select defaultValue={display}>
                    {titles.map((Name) => (
                        <option key={Name} value={Name}>
                            {Name}
                        </option>
                    ))}
                </select>
            </div>
        );
    }
}

我已经考虑过通过不访问“类别”来读取错误的 JSON 值是否是错误的,或者这是否与地图/列表有关。 我只需要名称值来填充选项。

来自初学者的感谢。

    标签: javascript reactjs json get


    【解决方案1】:

    你可以尝试做类似的事情

    response?.data?.map(({ Name }) => Name)
    

    或者

    response && responese.data && response.data.map((element, index) => {
       console.log('My data', element) // here you should see your data
    })
    

    为了确保我们拥有这些数据

    玩得开心!

    【讨论】:

    • 嗨,感谢您的建议,不幸的是它得到了错误:未捕获(承诺中)类型错误:response$data.map 不是函数
    • 我刚刚更新了我的答案,请检查一下
    【解决方案2】:

    通过检查响应长度,此错误将被删除

    response.data.length > 0 && response.data.map((element, index) => {
    console.log('My data', element) // here you should see your data
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-27
      • 2021-10-14
      • 1970-01-01
      • 2017-12-29
      • 2022-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多