【问题标题】:How can I change element inside of map function如何更改地图功能内的元素
【发布时间】:2022-01-20 09:17:23
【问题描述】:

如果按下按钮,我需要更改 selectedCountries 值。但是当我这样做时,地图功能会卡住并返回错误。


    <ul>
    {
       selectedCountries.map((countryName, i) => (
          <li key={i}>{countryName}<button onClick={() => {
             setSelectedCountries(countryName)
          }}>show</button></li>
       ))
    }
    </ul>

【问题讨论】:

  • selectedCountries 是一个数组(这是允许您映射它的原因)。当您将其设置为 countryName(可能是字符串)时,它不再是数组,因此地图崩溃。

标签: reactjs react-native react-hooks


【解决方案1】:

您应该定义除 selectedCountries 之外的另一个州,它包含国家/地区数组。
定义一个州 selectedCountry 并使用它来存储所选的国家/地区名称:

const [selectedCountry, setSelectedCountry] = useState('');

...

<ul>
  {selectedCountries.map((countryName, i) => (
    <li key={i}>
      {countryName}
      <button
        onClick={() => {
          setSelectedCountry(countryName);
        }}
      >
        show
      </button>
    </li>
  ))}
</ul>;

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多