gpt4 book ai didi

reactjs - 使用 "useReducer"时如何添加副作用?

转载 作者:行者123 更新时间:2023-12-03 13:32:57 28 4
gpt4 key购买 nike

如果我在使用 时需要添加一些副作用,我想知道我有哪些选择useReducer 钩。

例如,有一个 TODO-app:

const initialState = {items: []};

const reducer = (state, action) => {
switch (action.type) {
case 'ADD':
return {
...state,
items: [...state.items, action.newItem]
};

default:
throw new Error();
}
};

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

return (
<button onClick={() => dispatch({ type: 'ADD', newItem: 123 })}>
Add item
</button>
);
}

我需要将新项目保存到服务器。 问题是: 我应该把这段代码放在哪里?

(请记住, reducer 应该是纯的)

最佳答案

useEffect hook 可能是您想要使用的。顾名思义,它正是为每个渲染周期做副作用。一个小的重构以允许在组件中这样做。

const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const [newItem, setNewItem] = useState(null);

useEffect(
() => {
// new item! dispatch state update, send to server, and reset newItem
dispatch({ type: 'ADD', newItem });
sendNewItemToServer(newItem);
setNewItem(null);
},
[newItem],
);

const newItemHandler = item => setNewItem(item);

return (
<button onClick={() => newItemHandler(123)}>
Add item
</button>
);
}

当您的应用程序很小时,这很容易,但随着应用程序变大,您可能需要考虑应用程序级别的事件处理系统,例如 rxjs 和 redux/epics、redux sagas、redux thunk。这些都依赖于 redux 作为应用程序状态真相的主要来源,并且可以处理对 API 的异步调用以发送和检索数据。

关于reactjs - 使用 "useReducer"时如何添加副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60694264/

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