useEffect 状态更改后未触发

ben*_*hky 9 reactjs use-effect use-state

我正在制作一个自定义下拉列表,允许在下拉列表中推送新项目。由于某种原因,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);
    
      }
Run Code Online (Sandbox Code Playgroud)

在返回块中:

<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>
Run Code Online (Sandbox Code Playgroud)

k.s*_*.s. 17

在您的情况下,它没有被更改,因为在 JS 中,objectsarrays是通过引用进行比较,而不是通过值进行比较。

例如

let foo = {bar: 1}
let faz = foo
let notFoo = {bar: 1}
foo === faz // true
foo === notFoo // false
Run Code Online (Sandbox Code Playgroud)

话虽这么说,在这里:

 const categoryListArr = categoryList // you are passing categoryList by reference
 categoryListArr.push(newOption)
 setCategoryList(categoryListArr)
Run Code Online (Sandbox Code Playgroud)

你直接改变你的状态,这通常不好。为了使其正常工作,您需要categoryListArr以不可变的方式创建数组

 const categoryListArr = [...categoryList] // this is a new array, which contains the same items from the state
 categoryListArr.push(newOption)
 setCategoryList(categoryListArr)
Run Code Online (Sandbox Code Playgroud)

或者像这样

setCategoryList(prev => [...prev, newOption])
Run Code Online (Sandbox Code Playgroud)

现在你的useEffect意志被触发了。