【问题标题】:Dropdown from JSON response in React with hooks带有钩子的 React 中 JSON 响应的下拉列表
【发布时间】:2021-10-28 13:59:19
【问题描述】:

我想从我从 REST API 获得的数据中创建一个下拉列表。不幸的是,我已经尝试过的方法不起作用,下拉列表中没有显示任何内容。请参阅代码以供参考。它说'

×
TypeError: teams.current.map is not a function

'

我的对象看起来像

[
    {
        "id": 5,
        "name": "hasda"
    },
    {
        "id": 6,
        "name": "asdasd"
    }
]

我看了一下link,但没有多大帮助。 我希望你能帮助我

    import React, { useState, useEffect, useRef } from "react";
    import { useHistory } from "react-router-dom";
    import axios from 'axios'
    
    
    function Navbar() {
        const [team, setTeam] = useState([]);
    
    
        useEffect(() => {
            getTeams()
        }, []);
    
        const getTeams = () => {
            axios
                .get(`${process.env.REACT_APP_API_URL}/team/all`, {})
                .then((res) => {
                    console.log(res.data);
                    setTeam(res.data)
                })
                .catch((error) => {
                    console.log(error)
                })
        }
    
    
        return (
    
                 <p className="navbar-item">Mannschaften</p>
    
                 <div className="navbar-dropdown">
    
                 {/* {team.current.map((d, i) => (
    
                      <a className="navbar-item" href={i.mannschaftsname}>{i.mannschaftsname}</a>
    
                  ))}  */}



                 {/* {
                   this.state.team.map((obj) => {
                   return <option team={obj.id}>{obj.name}</option>
                    })
                 } */}

                   <a className="navbar-item" href="/login">Test</a>
                   </div>
            </div>

    );
}

export default Navbar;

【问题讨论】:

  • res.data的内容是什么
  • @Danial 看起来像这样 [ { "id": 5, "name": "hasda" }, { "id": 6, "name": "asdasd" } ]

标签: javascript reactjs json axios react-hooks


【解决方案1】:

您所在州的名称是团队而不是团队。 因此,您可以尝试以下方法:

<select>
{

     team?.map((obj) => {
          return <option team={obj.id}>{obj.name}</option>
     })  
}
</select>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2014-11-15
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多