我正在制作一个自定义的dropdown,它允许在下拉列表中推送新项目。由于某些原因,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);
}在return块中:
<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>发布于 2020-07-17 05:00:39
在你的例子中它没有被改变,因为在JS中你是objects和arrays是通过引用而不是值来比较的。
例如
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)现在,您的useEffect将被触发。
发布于 2020-07-17 05:01:03
问题是,您使用数组来比较和触发useEffect,所以它在最初呈现时触发,因为数组的长度发生了变化,但在随后的变化中,如果长度相同,并且只有任何元素发生了变化,则不会触发useEffect
您可以使用JSON.stringify
useEffect(() => {
console.log("categoryList::::::::::::::::", categoryList)
}, [JSON.stringify(categoryList)]);发布于 2020-07-17 05:05:21
只要改变就好
const categoryListArr = categoryList
categoryListArr.push(newOption)
setCategoryList(categoryListArr)在……里面
setCategoryList([...categoryList, newOption]);这将更改数组引用,并让效果触发。
https://stackoverflow.com/questions/62943332
复制相似问题