【问题标题】:Unable to use .map in dropdown menu ReactJs无法在下拉菜单 ReactJs 中使用 .map
【发布时间】:2022-12-03 22:04:47
【问题描述】:

我想用数据库中的数据填充下拉列表,disastertype 是一个包含所有详细信息的数组,但是当我通过它映射以显示 disaster_type 它不起作用时,该页面甚至不呈现显示空白页面。请指导,因为我是 REACTJS 的初学者。

  const [disastertype,Setdisastertype] = useState([]);
  useEffect(()=>{
    Axios.get("http://localhost:3001/api/disasterinfo").then((response)=>{
      Setdisastertype(response)
      console.log(response)

    })

  },[])
--------------------------------------------------------------------
 <td><div class="dropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Disaster Type</button>
        <ul class="dropdown-menu">
        {disastertype.map((val)=>(
            
            <li><a class="dropdown-item" key={val.disaster_type}>{val.disaster_type}</a></li>
            
        ))}
          </ul>
       
        </div></td>

来自 console.log(response) 的结果 console.log

【问题讨论】:

  • disastertype是数组还是对象,能不能包含对象json
  • @Azzy const [disastertype,Setdisastertype] = useState([]); useEffect(()=>{ Axios.get("localhost:3001/api/disasterinfo").then((response)=>{ Setdisastertype(response) console.log(response) }) },[])
  • 代码似乎没问题,但是您能否编辑问题并将代码放在那里,还包括来自开发工具的 console.log 的输出,这将帮助社区成员提供更好的答案
  • 为disastertype设置新状态时,您应该使用response.data
  • @RubenSmn 成功了!!谢谢

标签: node.js reactjs bootstrap-4 drop-down-menu


【解决方案1】:

你只是错过了一个领域,你有两个选择:

  1. 将Setdisastertype(response)更改为Setdisastertype(response.data)
  2. 将disastertype.map更改为disastertype.data.map

    推荐第一种解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多