我想知道如果在使用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>
);
}
Run Code Online (Sandbox Code Playgroud)
我需要将新项目保存到服务器。问题是:我应该把这段代码放在哪里?
(记住,reducer应该是纯的)
The useEffect hook is likely what you'd want to use. As the name suggests, it's precisely for doing side-effects per each render cycle. A small refactor to allow this within the component.
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>
);
}
Run Code Online (Sandbox Code Playgroud)
This is easy while your app is small, but as it get larger you may want to consider an app level event handling system, such as rxjs & redux/epics, redux sagas, redux thunks. These all rely on redux as the main source of app state truth and can handle the asynchronous calls to API's to send and retrieve data.
| 归档时间: |
|
| 查看次数: |
2862 次 |
| 最近记录: |