【问题标题】:Problem with rendering correct select option in React在 React 中呈现正确选择选项的问题
【发布时间】:2022-07-16 11:11:32
【问题描述】:

我有一个国家/地区列表,如下所示

 export const countryList = [
      " ",
      "Afghanistan",
      "Africa",
      "Albania",
      "Algeria",
      "Andorra",
      "Angola", ...]

然后我将这些数据导入 React Js 文件并通过它进行映射。每次迭代都应该返回一个带有值的选项标签。像下面这样:

   import React, { useContext, useState, useRef } from "react";
import { DataContext } from "../App";
import { countryList } from "../data/countryList";

const Dropdown = (props) => {
  const selectedCountry = useRef(null);
  const { covidData } = useContext(DataContext);
  const [countryName, setCountryName] = useState("");

  console.log(covidData);
  return (
    <article>
      <select
        name="countries"
        id="countries"
        ref={selectedCountry}
        onChange={(e) => {
          setCountryName(e.target.value);
          console.log(countryName);
        }}
      >
        {countryList.map((country) => {
          return (
            <option value={country} key={country}>
              {country}
            </option>
          );
        })}
      </select>
    </article>
  );
};

export default Dropdown;

这些代码创建了一个包含所有值的下拉列表,并且 select 有一个 Ref 挂钩,该挂钩抓取 select 的值,并在更改时使用 useState 挂钩更改变量的值。

无论如何,问题是当我第一次单击下拉选项时,我在 console.log 中看到一个空字符串,但在下一次单击时,我看到的是一个县的名称,但没有看到我单击的相应国家.我知道这听起来令人困惑,但这里有一个非常短的视频:https://www.loom.com/share/84a88f1cc8fe4d3995962ea926c20559?sharedAppSource=personal_library

如果这还不够,这是我的完整代码:https://github.com/timothyroybd/covid-tracker-react/tree/incubator

提前谢谢你!

【问题讨论】:

  • setState异步你不能在更新后使用console.log,你总是会看到以前的值。

标签: javascript reactjs select event-listener


【解决方案1】:

试试这个代码,它的工作原理

import "./styles.css";

import { CountryList } from "./data";
import { useState } from "react";

export default function App() {
  const [country, setCountry] = useState("");

  const setCountryName = (e) => {
    console.log(e);
  };

  return (
    <div className="App">
      <article>
        <select
          name="countries"
          id="countries"
          onChange={(e) => {
            setCountryName(e.target.value);
          }}
        >
          {CountryList.map((country) => {
            return (
              <option value={country} key={country}>
                {country}
              </option>
            );
          })}
        </select>
      </article>
    </div>
  );
}

【讨论】:

    【解决方案2】:

    看看这个。您可以通过这种方式使其变得简单。

    import React, { useContext } from 'react'
    import { DataContext } from '../App'
    import { countryList } from '../data/countryList'
    
    const Dropdown = ({ formHandler }) => {
      // const selectedCountry = useRef(null)
      const { covidData } = useContext(DataContext)
      // const [countryName, setCountryName] = useState('')
    
      // console.log(covidData)
      return (
        <article>
          <select
            name='countries'
            id='countries'
            onChange={(e) => {
              console.log('In dropdown', e.target.value)
              formHandler(e.target.value)
              // setCountryName(e.target.value)
              // It will not show you the changed value because it's react state. That's why when you console log for the first time it will show "" string and later if you changed again it will show you the old value
              // console.log(countryName)
            }}
          >
            {countryList.map((country) => {
              return (
                <option value={country} key={country}>
                  {country}
                </option>
              )
            })}
          </select>
        </article>
      )
    }
    
    export default Dropdown
    
    

    要了解有关反应状态异步主题的更多信息,请查看article

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2019-09-02
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多