gpt4 book ai didi

javascript - 可以对状态进行引用(来自 reducer )以避免创建新的回调吗?

转载 作者:行者123 更新时间:2023-12-05 05:49:29 25 4
gpt4 key购买 nike

我经常有一个用例,在 reducer 中有一些状态,它也需要在一些回调 (useCallback) 中访问

const [state, dispatch] = useReducer(reducer, initialState);
...
const handleAction = useCallback(()=>{
// dependency on state
},[])

为了避免在每次状态更改时都运行 useCallbacks,我找到了一个 ref 并在每次渲染时都为其分配了状态

 stateRef.current = state;

然后我必须在回调中使用来自状态的东西的地方,它是从 stateRef 访问的。这是正确的做法吗?

最佳答案

如果您只是从组件主体更新 stateRef 那么这不是最正确的方法,因为这将被视为无意的副作用。如果不使用依赖于 stateuseCallback Hook 将当前状态值重新包含在回调函数中,则使用 useEffect建议依赖于状态值。

const [state, dispatch] = useReducer(reducer, initialState);
const stateRef = useRef();

useEffect(() => {
stateRef.current = state;
}, [state]);

const handleAction = ()=>{
// access stateRef.current
};

虽然这实际上是 useCallback 完成的,但方式更简洁。

const [state, dispatch] = useReducer(reducer, initialState);

const handleAction useCallback(() => {
// access current state value closed over in scope
}, [state]);

关于javascript - 可以对状态进行引用(来自 reducer )以避免创建新的回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70660439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com