【问题标题】:State is not updating immediately after onClick in react js在反应 js 中的 onClick 后状态不会立即更新
【发布时间】:2021-02-18 02:10:37
【问题描述】:

我点击复选框。当我选中复选框时,我正在尝试更新状态,但它没有立即更新。我创建了一个名为 handleAllCheckbox 的 onchange 事件。

这是我的代码 - const [hello, setHello] = useState(false);

const handleAllCheckbox = (e) => {


    setHello(!hello);

    if (!hello) {
      contactList.map((item) => {
        Ids.push(item._id)
      });
      setTheArray(...theArray, Ids);
    }
    else {
      const newIds = []
      setTheArray(...theArray, newIds);
    }
  }

如果hellotrue,那么theArray 必须有ID,如果它是假的,那么theArray 应该是空的。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    如果你想处理任何副作用,你应该使用useEffect,副作用是指do something when a particular state change。所以在你的情况下可能可以参考下面

    import { useState, useEffect } from 'react';
    
    const [hello, setHello] = useState(false);
    
    useEffect(() => {
      if (!hello) {
        contactList.map((item) => {
          Ids.push(item._id)
        });
        setTheArray(...theArray, Ids);
      }
      else {
        const newIds = []
        setTheArray(...theArray, newIds);
      }
    }, [hello]);
    
    
    const handleAllCheckbox = () => setHello(!hello);
    

    注意[hello]作为useEffect的第二个参数,表示do something whenever "hello" state is updated。所以现在你的代码也更干净了,handleAllCheckbox 只关心处理状态hello,每当hello 的值被更新时,useEffect 就会处理这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2018-08-05
      • 2021-05-20
      相关资源
      最近更新 更多