【问题标题】:how to map json data in dropdown list (Functional component)?如何在下拉列表(功能组件)中映射 json 数据?
【发布时间】:2021-05-30 21:44:09
【问题描述】:
export default function FirstStep() {
  const [ageGroup, setAgeGroup] = useState('');

  function getAgeGroup(){
    axios.get(`http://localhost:1190/v1/ageGroup`)
      .then(res => {
        console.log(res);
      })
  }

<Form.Label className="Form-Label">Age</Form.Label>
                  <Dropdown>
                    <Dropdown.Toggle className="Field-Color" style={{ width: '100%'}}>
                      Dropdown Button
  </Dropdown.Toggle>

                    <Dropdown.Menu style={{ width: '100%' }}>
                      <Dropdown.Item  >Action</Dropdown.Item>
                      <Dropdown.Item >Another action</Dropdown.Item>
                      <Dropdown.Item >Something else</Dropdown.Item>
                    </Dropdown.Menu>
                  </Dropdown>
}

my JSON 
[{"id":"1","ageGroup":"6 to 16 years","categories":[{"categoryName":"DANCE","description":"blah blah","imageURL":"imgUrl","styles":["JAZZ","CONTEMPORARY"]}]},

{"id":"2","ageGroup":"18 岁及以上","categories":[{"categoryName":"DANCE","description":"blah blah","imageURL":" imgUrl","styles":["HIP HIP","ZUMBA"]}]}]

//Mapping is not my strongest front, please let me know how the age group can be mapped into the dropdown. 

【问题讨论】:

    标签: reactjs mapping dropdown react-functional-component


    【解决方案1】:

    其实,你只需要在获取它并循环遍历它时设置ageGroups

       function getAgeGroup(){
        axios.get(`http://localhost:1190/v1/ageGroup`)
          .then(res => {
            console.log(res);
            setAgeGroup(res.data)
          })
      }
    
    
    
             <Dropdown.Menu style={{ width: '100%' }}>
                              {ageGroup?.map((value,indx)=>{
                               return (
                                 <Dropdown.Item key={indx}>{value.ageGroup}</Dropdown.Item>
                               )})
                            </Dropdown.Menu>
                          </Dropdown>

    【讨论】:

    • 它抛出错误。先关闭表达式,然后得到ageGroup.map is not a function
    • 哦,你用一个空字符串初始化了状态但是它应该是一个像这样的空数组 const [ageGroup, setAgeGroup] = useState([]);
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多