其实一开始看到useReducer的时候,还以为它跟react的好伙伴redux有什么关系。然而也就是借鉴了redux的设计模式的状态操作工具而已。
目前使用Redux的小伙伴们可能还需要用原来的react-redux提供的connect HOC一段时间。尽管facebook已经在做相关的hook,目前还处于不稳定的状态,使用后果自负(项目地址:https://github.com/facebookincubator/
回到useReducer,它的存在是为一步操作更新多个状态设计。
举个不太恰当的拉数据的例子。通常拉数据的时候需要显示表示正在“加载中”的动画,加载数据出错则需要提示相关的错误,成功则显示数据。这里我们假设有2个状态值isLoading和 error,加载成功的数据则是由react-redux从props里传进来:
- 加载中:
isLoading = true; error = undefined; data = undefined | { ... };
- 成功:
isLoading = false; error = undefined; data = { ... };
- 失败:
isLoading = false; error = ‘Error message.’; data = { ... };
比较容易想到的做法是用useState,如下:
function MyComponent({
loadDataAction, data }) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(undefined);
const loadData = useCallback(async () => {
setIsLoading(true);
setError(undefined);
try {