Ana*_*ngh 3 javascript reactjs react-hooks use-state
我使用 React 创建了新的自定义选择框。我在组件加载时加载了预先填充的数组(使用 useEffect)。当用户搜索任何不存在的国家/地区时,会有一个添加选项。于是我对 useState 着迷了。代码如下:-
const [countries, setCountries] = useState([]);
Run Code Online (Sandbox Code Playgroud)
国家列表:-
[
{"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()
})
Run Code Online (Sandbox Code Playgroud)
我正在检查数组中搜索到的国家/地区,如果不存在,我只需添加到数组中
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
}
}
Run Code Online (Sandbox Code Playgroud)
问题是它没有更新,尽管我可以看到updatedVal 中的数据。
整个代码在这里:-
问题似乎是您传递给其引用未更改的useState()数组 ( updatedVal),因此 React 似乎认为您的数据尚未修改,并且它会在不更新您的状态的情况下退出。
尝试删除不必要的变量并直接执行setCountries([...countries, obj])
我可能建议对您的代码进行另一个小修复:您可以使用它Array.prototype.every()来确保每个现有项目都有不同的label. 它有两个优点.filter()- 它会在遇到重复项(如果存在)时立即停止循环,并且不会继续直到数组末尾(正如.filter()所做的那样),因此不会减慢不必要的重新渲染并且返回布尔值,所以你实际上不需要额外的变量。
以下是该方法的快速演示:
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
)Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)