我熟悉 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))
使用效果: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}));
}, []);
最佳答案
这两种设置本质上是相似的。你可以用这两种方法做同样的事情。
使用与您在此处编写的代码完全相同的代码,createAsyncThunk
有一个主要优势。接近,因为它会catch
API 调用中发生的任何错误。它将通过调度 fetchUserById.rejected
来响应这些错误。操作而不是 fetchUserById.fulfilled
行动。您的 reducer 没有响应 rejected
很好的案例。错误仍然被捕获。与您的useEffect
您冒着“Promise 中 Uncaught Error ”错误的风险。
现在当然可以catch
你自己的错误。您也可以dispatch
一个 pending
效果开始时的 Action 。但是一旦你开始这样做,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 })
);
}, []);
关于javascript - Redux createAsyncThunk vs useEffect hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67040344/