使用反应钩子在 REACTJS 中使用数组填充动态下拉列表的步骤 [英] Steps to populate dynamic Dropdown using arrays in REACTJS using react hooks

查看:22
本文介绍了使用反应钩子在 REACTJS 中使用数组填充动态下拉列表的步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我的知识不足,因为我对 ReactJS 还很陌生.我正在尝试创建一个动态 Dropdown 系统,其中我有 The Country DropDown 和城市 DropDown,我想从一个包含多个数组的常量中获取我的数据,这是我拥有的常量示例:

const countries = {"France":["Paris","Marseille","Lille","Lyon"],美国":[纽约"、旧金山"、奥斯汀"、达拉斯"]};

我知道我需要使用 useState 和 useEffect 钩子和一个函数来处理事件变化.

我很难弄清楚如何处理数据格式,尤其是const里面的变量不容易被访问,如果数据在这个里面就容易多了形状:

const 国家 =[{名称:'美国',城市:[纽约",旧金山",奥斯汀",达拉斯"]},{名称:'法国',城市:[巴黎",马赛",里尔",里昂"]},]

但不幸的是,第一个样本是我必须处理的数据形状,我无法手动修改它,因为我有非常大的数据样本.所以如果有人可以简单地指导我进入我应该做的步骤,我将不胜感激.

解决方案

您可以使用Object.keys"在单独的列表中抽象国家/地区并使用第一个来获取城市.我认为在这种情况下你不需要使用useEffect".

示例:https://codesandbox.io/s/dropdown-react-p0nj7

import React, { useState } from "react";导入./styles.css";导出默认函数 App() {const [城市,setCities] = useState([]);const [selectedCounty, setSelectedCountry] = useState("");const [selectedCity, setSelectedCity] = useState("");const 国家 = {法国:[巴黎"、马赛"、里尔"、里昂"]、美国:[纽约"、旧金山"、奥斯汀"、达拉斯"]、巴西:[圣保罗"、里约热内卢"、萨尔瓦多"]};const countryList = Object.keys(countries).map(key => ({名称:钥匙}));函数 handleCountrySelect(e) {console.log(选定的国家",e.target.value);const countrySel = e.target.value;const citysSel = countrySel !== "";?国家 [countrySel] : [];setSelectedCountry(countrySel);设置城市(城市塞尔);setSelectedCity("");}函数 handleCitySelect(e) {console.log(选定的城市",e.target.value);const citysel = e.target.value;setSelectedCity(citiesSel);}返回 (

<h1>下拉式国家和城市示例</h1><div className="容器"><选择名称=国家"onChange={e =>handleCountrySelect(e)}值={selectedCounty}><option value="">选择国家</option>{countryList.map((country, key) => (<option key={key} value={country.name}>{国家的名字}</选项>))}</选择><选择名称=城市"onChange={e =>handleCitySelect(e)}值={selectedCity}><option value="">选择城市</option>{cities.map((city, key) => (<option key={key} value={city}>{城市}</选项>))}</选择>

);}

Excuse my lack of knowledge as i am fairly new to ReactJS. I'm trying to create a dynamic Dropdown system where i have The Country DropDown and the cities DropDown, and i want to fetch my data from a const that has multiple arrays in it, here's an example of the const i have:

const countries = {"France":["Paris","Marseille","Lille","Lyon"],
                   "Usa":["New York","San Francisco","Austin","Dallas"]
                  };

I know that i need to use the useState and the useEffect hooks and a function to handle the event changes.

What i'm having a hard time to figure out is how to deal with the data format, especially that the variables inside the const can't be accessed easily, it would've been much easier if the data was in this shape:

const countries =[
                   { name: 'Usa',  cities: ["New York", "San Francisco", "Austin", "Dallas"]},
                   { name: 'France', cities: ["Paris", "Marseille", "Lille", "Lyon"]},
                 ]

But unfortunately the first sample is the shape of data i have to deal with and i can't modify it manually because i have a very large sample of data. So if anyone could just direct me briefly into the steps i should make, i would be very thankful.

解决方案

You can abstract the country in a separate list with the "Object.keys" and use the first one to get the cities. I think in this case you don't need to use "useEffect".

Example here: https://codesandbox.io/s/dropdown-react-p0nj7

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [cities, setCities] = useState([]);
  const [selectedCounty, setSelectedCountry] = useState("");
  const [selectedCity, setSelectedCity] = useState("");

  const countries = {
    France: ["Paris", "Marseille", "Lille", "Lyon"],
    Usa: ["New York", "San Francisco", "Austin", "Dallas"],
    Brazil: ["São Paulo", "Rio de Janeiro", "Salvador"]
  };

  const countryList = Object.keys(countries).map(key => ({
    name: key
  }));

  function handleCountrySelect(e) {
    console.log("Selected country", e.target.value);
    const countrySel = e.target.value;
    const citiesSel = countrySel !== "" ? countries[countrySel] : [];
    setSelectedCountry(countrySel);
    setCities(citiesSel);
    setSelectedCity("");
  }

  function handleCitySelect(e) {
    console.log("Selected city", e.target.value);
    const citiesSel = e.target.value;
    setSelectedCity(citiesSel);
  }

  return (
    <div className="App">
      <h1>Example DropDown Coutries and Cities</h1>

      <div className="Container">
        <select
          name="Countries"
          onChange={e => handleCountrySelect(e)}
          value={selectedCounty}
        >
          <option value="">Select the country</option>
          {countryList.map((country, key) => (
            <option key={key} value={country.name}>
              {country.name}
            </option>
          ))}
        </select>

        <select
          name="Cities"
          onChange={e => handleCitySelect(e)}
          value={selectedCity}
        >
          <option value="">Select the city</option>
          {cities.map((city, key) => (
            <option key={key} value={city}>
              {city}
            </option>
          ))}
        </select>
      </div>
    </div>
  );
}

这篇关于使用反应钩子在 REACTJS 中使用数组填充动态下拉列表的步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆