我正在制作一个自定义下拉列表,允许在下拉列表中推送新项目。由于某种原因,useEffect 不会在状态更改时触发,但会在初始渲染时触发。我很确定我错过了一些小东西,但看不到它。当用户单击与“addNewOptionToTree”方法关联的按钮时,应推送新项目。然后,categoryList 应在下拉列表中显示新项目。控制台日志被触发并且新的 arr 出现......有什么想法吗?
以上返回:
const [newOption, setNewOption] = useState('')
const [categoryList, setCategoryList] = useState(["Calendars", "Meetings", "Apostrophes work!"])
useEffect(() => {
console.log("categoryList::::::::::::::::", categoryList)
}, [categoryList]);
function addNewOptionToTree() {
console.log('category:', categoryList);
console.log('newOption:', newOption);
const categoryListArr = categoryList
categoryListArr.push(newOption)
setCategoryList(categoryListArr)
console.log("category:", categoryListArr);
}
在返回块中:
<div className='dropDownList'>
<div className='listItem' key={'add-item-key'}>
<Input
type='text'
label=''
value={newOption}
placeholder='Add New Category'
onChange={val => setNewOption(val)}
/>
<div className='icon-add-contain dropdown-add-btn' onClick={addNewOptionToTree}></div>
</div>
{
categoryList.length > 0 &&
categoryList.map((category, index) => (
<div className='listItem' onClick={onOptionClicked(category)} key={'level1-'+index}>
{category}
</div>
))
}
</div>
就你而言,它没有被改变,因为objects
and arrays
在 JS 中通过引用进行比较,而不是通过值进行比较。
例如
let foo = {bar: 1}
let faz = foo
let notFoo = {bar: 1}
foo === faz // true
foo === notFoo // false
话虽这么说,在这里:
const categoryListArr = categoryList // you are passing categoryList by reference
categoryListArr.push(newOption)
setCategoryList(categoryListArr)
你直接改变你的状态,这通常不好。为了使其正常工作,您需要创建您的categoryListArr
以不可变的方式数组
const categoryListArr = [...categoryList] // this is a new array, which contains the same items from the state
categoryListArr.push(newOption)
setCategoryList(categoryListArr)
或者像这样
setCategoryList(prev => [...prev, newOption])
现在你的useEffect
将被触发。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)