【问题标题】:I got this error: "State updates from the useState() and useReducer() Hooks don't support the second callback..." when i make a change in my state我收到此错误:“来自 useState() 和 useReducer() Hooks 的状态更新不支持第二个回调...”当我更改状态时
【发布时间】:2019-10-23 07:32:54
【问题描述】:

我粘贴在标题中的句子是我从我的代码中得到的,我正在尝试使用钩子来改变数组中的状态,这是我的代码。

export default function card(){
 let array = [true,false]

    const [change, setChange]=useState(array)


    function toggleIcon() {
        setChange(
            ...change,
            change[0]=!change[0]
        )
 console.log(change)
     }
return(
</Fragment>
    { change[0] ? (<p>hi</p>): (<p>bye</p>)}
</Fragment>
)

}

这个我得到了第一个变化,我把你改成再见......但是当我再次点击它时,你得到了这个错误 MyContracts.js:18

未捕获的类型错误:更改不可迭代

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    您解构错误,请尝试下面的代码,您不必解构,但如果您想尝试,仍然有注释代码。

    function toggleIcon() {
            //let newState = [...change];
            //newState[0] = !change[0];
            //setChange(newState);
    
            change[0]=!change[0]
            setChange(change);
            console.log(change)
         }
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多