如何在`setState`中附加某些操作?

huangapple go评论44阅读模式
英文:

How can i attach something to happen on setState const

问题

我有

const [items, setItems] = useState([])

当调用 setItems() 时,如何添加一个额外的操作呢?可以尝试以下方式(这不是有效的方式):

const setItems = (items) => {
    // 首先执行一些操作
    // 然后调用 setItems
}

也可以将其传递给另一个函数,然后稍后再调用实际的 setItems(),但我想知道是否可以覆盖原始的 setItems 函数。

英文:

i have

const [items, setItems] = useState([])

how can I add one more action to happen when firing setItems(), so something like (which is not valid)

const setItems = (items) =>{
    // do something first
    // then call the setItems
}

it's possible to pass it to another function first then call the actual setItems() later, but I was wondering if its possible to override the original setItems function.

答案1

得分: 1

你可以在中间函数中调用 setItems

const handleSetItems = (params) => {
    setItems(prevItems => {
        // 先执行一些操作
        // 然后调用 setItems
        return prevItems; // 要设置到 items 状态的数据
    });
}

或者你也可以在设置函数内部执行操作,如下所示:

setItems(prevItems => {
    // 先执行一些操作
    // 然后调用 setItems
    return prevItems;
});
英文:

you can add an intermediate function as call setItems from that function.

const handleSetItems = (params) => {
    setItems (prevItems) =>{
        // do something first
        // then call the setItems
        return prevItems; // data to be set in items state
    }
    }

Or you can do within setter function as following

setItems (prevItems =>{
            // do something first
            // then call the setItems
            return prevItems; 
        })

huangapple
  • 本文由 发表于 2023年2月19日 14:28:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定