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

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

问题描述

请原谅我缺乏知识,因为我还不熟悉ReactJS。我正在尝试创建一个动态Dropdown系统,其中有The Country DropDown和城市DropDown,并且我想从其中具有多个数组的const提取数据,这是我拥有的const的示例:

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"]
                  };

我知道我需要使用useState和useEffect挂钩以及一个用于处理事件更改的函数

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

我很难弄清楚如何处理数据格式,尤其是const内部的变量不易访问,如果数据是这样的形状,那就容易多了:

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"]},
                 ]

但不幸的是第一个样本是我必须处理的数据形状,我无法手动修改它,因为我有非常大的数据样本。
因此,如果有人能将我简短地介绍给我应该做的步骤,
i将非常感激。

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.

推荐答案

您可以使用 Object.keys在一个单独的列表中抽象该国家,然后使用第一个城市来获取城市。我认为在这种情况下,您无需使用 useEffect。

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".

此处的示例: 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>
  );
}

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

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