tok*_*chi 13 javascript reactjs redux react-redux
我熟悉react hooks,我发现使用useEffect非常容易,thunk很难处理,我可以只使用useEffect和axios并将结果分派到商店而不使用createAsyncThunk吗?与 useEffect 相比,使用它有什么主要的性能优势吗?
创建AsyncThunk:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'
// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[fetchUserById.fulfilled]: (state, action) => {
// Add user to the state array
state.entities.push(action.payload)
}
}
})
// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))
Run Code Online (Sandbox Code Playgroud)
使用效果:
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux'
import { userAPI } from './userAPI'
import axios from 'axios';
function App() {
const dispatch = useDispatch()
useEffect(() => {
axios
.get(userAPI)
.then(response => dispatch({type:'fetchUsers',payload:response.data}));
}, []);
Run Code Online (Sandbox Code Playgroud)
这两个设置本质上是相似的。您可以使用这两种方法做同样的事情。
使用与此处编写的代码完全相同的代码,该createAsyncThunk方法有一个主要优点,因为它可以catch解决 API 调用中发生的任何错误。它将通过调度一个fetchUserById.rejected操作而不是一个fetchUserById.fulfilled操作来响应这些错误。您的减速器没有响应这种rejected情况,这很好。错误仍然被捕获。您useEffect将面临“Promise 中未捕获的错误”错误的风险。
当然,现在您可以catch自己解决错误。您还可以在效果开始时执行操作dispatch。pending但是一旦你开始这样做,createAsyncThunk相比之下可能会感觉容易得多,因为它会自动调度pending、fulfilled和rejected操作。
useEffect(() => {
dispatch({ type: "fetchUsers/pending" });
axios
.get(userAPI)
.then((response) =>
dispatch({ type: "fetchUsers", payload: response.data })
)
.catch((error) =>
dispatch({ type: "fetchUsers/rejected", payload: error.message })
);
}, []);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6336 次 |
| 最近记录: |