反应 useState() 数组不更新

React useState() array not updating

我使用 React 创建了新的自定义选择框。有一个预填充的数组,我正在加载组件加载(使用 useEffect)。当用户搜索任何不存在的国家时,将有一个添加选项。所以我使用 useState 上瘾了。代码如下:-

const [countries, setCountries] = useState([]);

国家列表:-

[
  {"value": 1, "label": "Singapore"},
  {"value": 2, "label": "Malaysia"},
  {"value": 3, "label": "Indonesia"},
  {"value": 4, "label": "Phillipines"},
  {"value": 5, "label": "Thailand"},
  {"value": 6, "label": "India"},
  {"value": 7, "label": "Australia"},
  {"value": 8, "label": "Pakistan"}
]


const handleHTTPRequest = () => {
    service.getData() 
    .then(res => {
      setCountries(res);
    })
    .catch((err) => console.error(err))
  }

  useEffect(() => {
    handleHTTPRequest()
  })

我正在检查数组中搜索到的国家,如果不存在,我只需添加到数组中

const addCountry = (country) => {
    let isRecordExist = countries.filter(c => c.label === country).length > 0 ? true : false;
    const obj = {
      value: countries.length + 1,
      label: country
    }
    let updatedVal = [...countries, obj]
    
    setSelectedCountry(country)

    if (!isRecordExist) {
      **setCountries**(updatedVal) // updating array
    }
  }

问题是它没有更新,虽然我可以在 updatedVal 中看到数据。

完整代码在这里:-

https://github.com/ananddeepsingh/react-selectbox

问题似乎是您正在向 useState() 传递其引用未更改的数组 (updatedVal),因此在 React 看来您的数据未被修改并且它 bails out without updating your state.

尝试删除不必要的变量并直接执行 setCountries([...countries, obj])

我建议对您的代码进行另一个小修正:您可以使用 Array.prototype.every() 来确保每个现有项目都有不同的 label。与 .filter() 相比,它有两个优点 - 它会在遇到重复项时立即停止循环(如果存在)并且不会继续进行到数组末尾(如 .filter() 所做的那样),因此不会减慢速度不必要地重新渲染它 returns 布尔值,所以你实际上不需要额外的变量。

以下是该方法的快速演示:

const { useState, useEffect } = React,
      { render } = ReactDOM,
      rootNode = document.getElementById('root')
      
const CountryList = () => {
  const [countries, setCountries] = useState([])
  
  useEffect(() => {
    fetch('https://run.mocky.io/v3/40a13c3b-436e-418c-85e3-d3884666ca05')
      .then(res => res.json())
      .then(data => setCountries(data))
  }, [])
  
  const addCountry = e => {
    e.preventDefault()
    const countryName = new FormData(e.target).get('label')
    if(countries.every(({label}) => label != countryName))
      setCountries([
        ...countries,
        {
          label: countryName,
          value: countries.length+1
        }
      ])
    e.target.reset()
  }
  
  return !!countries.length && (
    <div>
      <ul>
        {
          countries.map(({value, label}) => (
            <li key={value}>{label}</li>
          ))
        }
      </ul>
      <form onSubmit={addCountry}>
        <input name="label" />
        <input type="submit" value="Add country" />
      </form>
    </div>
  )
}

render (
  <CountryList />,
  rootNode
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

我找到了根本问题。在您的 Select Box 组件中,您有:

 const [defaultValueoptions, setdefaultValueoptions] = useState(options);

应该是:

 const [defaultValueoptions, setdefaultValueoptions] = useState([]);

  useEffect(() => {
    setdefaultValueoptions(options);
  }, [options]);

问题是您没有更新 SelectBox 组件中的国家/地区列表。国家列表不应由 App 组件管理,而应由 SelectBox 组件管理,因为它是有状态组件。您试图通过更改 App 组件的状态来让 React 重新渲染您的 SelectBox 组件,但这是行不通的。嗯,它会重新渲染,因为你更改了一个道具 options,但它使用 defaultValueoptions 来显示你永远不会更新的选项。

将此添加到您的 SelectBox 组件:

useEffect(() => {
  setDefaultValueOptions(options);
}, [options]);

并将第 9 行更改为:

const [defaultValueoptions, setDefaultValueOptions] = useState(options);

编辑 我没有看到 Talmacel Marian Silviu 已经编辑了他的答案: