在我的反应项目中,我有以下代码。
import uuid from 'uuid';
import { SET_ALERT, REMOVE_ALERT } from './types';
export const setAlert = (msg, alertType, timeout = 5000) => dispatch => {
const id = uuid.v4();
dispatch({
type: SET_ALERT,
payload: { msg, alertType, id }
});
setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout);
};
Run Code Online (Sandbox Code Playgroud)
这里就用到了thunk。我将 saga 应用到项目中,我想用 saga 重写。由于没有 API 调用,我不想通过 saga 发送到减速器。我想从这个action直接转到reducer。那么如何在不发送的情况下重写呢?
我在使用 Typescript 调度 redux-thunk 操作时遇到问题。
import { AnyAction, applyMiddleware, createStore } from 'redux'
import thunk, { ThunkAction } from 'redux-thunk'
interface State {
counter: number
}
const initialState: State = {
counter: 10
}
function reducer(state = initialState, action: AnyAction) {
switch (action.type) {
case 'increment':
return { counter: action.payload }
default:
return state
}
}
function increment(): ThunkAction<void, State, unknown, AnyAction> {
return async function (dispatch) {
dispatch({
type: 'increment',
payload: 20
})
}
}
const store = createStore(reducer, …Run Code Online (Sandbox Code Playgroud) 我不久前制作了一个待办事项列表,作为练习 React 和 Redux 的一种方式。现在我正在尝试使用 redux 工具包重写它,但在操作创建者方面遇到了一些麻烦。
这是旧的动作创建者:
export const changeDescription = (event) => ({
type: 'DESCRIPTION_CHANGED',
payload: event.target.value })
export const search = () => {
return (dispatch, getState) => {
const description = getState().todo.description
const search = description ? `&description__regex=/${description}/` : ''
axios.get(`${URL}?sort=-createdAt${search}`)
.then(resp => dispatch({ type: 'TODO_SEARCHED', payload: resp.data }))
} }
export const add = (description) => {
return dispatch => {
axios.post(URL, { description })
.then(() => dispatch(clear()))
.then(() => dispatch(search()))
} }
export const …Run Code Online (Sandbox Code Playgroud) 我在这里描述了这个确切的问题https://github.com/reduxjs/redux-toolkit/issues/485#issuecomment-610654378
所以我直接导入了 ThunkDispatch 并使用它。我无法从调度的响应中获取任何密钥而不引发property does not exist错误
@reduxjs/toolkit@1.5.1
Run Code Online (Sandbox Code Playgroud)
const response = await dispatch(deactivateSubscription(args))
Run Code Online (Sandbox Code Playgroud)
const response: PayloadAction<ApiResponse<EmptyBodyResponse>, string, {
arg: DeactivateSubscriptionArgs;
requestId: string;
requestStatus: "fulfilled";
}, never> | PayloadAction<...>
Run Code Online (Sandbox Code Playgroud)
export interface ApiResponse<T = unknown> {
body: T
error: Error
success: boolean
message?: string
}
Run Code Online (Sandbox Code Playgroud)
TS2339: Property 'error' does not exist on type 'PayloadAction<ApiResponse<EmptyBodyResponse>, string, { arg: DeactivateSubscriptionArgs; requestId: string; requestStatus: "fulfilled"; }, never> | PayloadAction<...>'.
Property 'error' does not exist on type 'PayloadAction<ApiResponse<EmptyBodyResponse>, string, { arg: DeactivateSubscriptionArgs; requestId: …Run Code Online (Sandbox Code Playgroud) 如果用户未注册,API 会抛出 401。但即使有错误,extraReducers 也会执行已完成的情况。500 和其他错误也会发生这种情况。
额外减速器
extraReducers: (builder) => {
builder
.addCase(login.pending, function (state) {
console.log("pending");
state.isLoading = true;
})
.addCase(login.fulfilled, (state, action) => {
console.log("fullfield");
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(login.rejected, (state, action) => {
console.log("rejected");
console.log(action.payload);
state.isLoading = false;
state.error = true;
state.message = action.payload;
state.user = null;
});
}
Run Code Online (Sandbox Code Playgroud)
asyncThunk登录方法
export const login = createAsyncThunk("auth/login", async (user, thunkAPI) => {
try {
let user = await authService.login(user);
return user;
} catch (error) …Run Code Online (Sandbox Code Playgroud) 我一直在尝试使用 Redux 工具包进行身份验证刷新令牌调用,但在安装所有修复程序后,它现在仍然能够读取错误消息。
设置 axios 实例:
export const axiosInstance = axios.create({
baseURL: REACT_APP_API_URL,
});
Run Code Online (Sandbox Code Playgroud)
进行API调用:
export const refreshAccessAndRefreshTokens = async () => {
const response = await axiosInstance({
method: 'post',
url: '/refresh-tokens',
withCredentials: true,
});
return response;
};
Run Code Online (Sandbox Code Playgroud)
thunk函数:
// GET ACCESS TOKEN USING REFRESH TOKEN
export const refreshTokens = createAsyncThunk(
'auth/refreshTokens',
async ({ rejectWithValue }) => {
try {
const response = await refreshAccessAndRefreshTokens();
return response.data;
} catch (error) {
console.log('error', error);
console.log('data', error.response.data);
console.log('message', error.response.data.message);
return rejectWithValue(error.response.data.message);
} …Run Code Online (Sandbox Code Playgroud) 我正在使用useSelector钩子来检索我的减速器的值,但它导致我的应用程序上出现大量不必要的渲染。
我在组件上使用哪个属性并不重要,因为它们都state从减速器获取相同的对象,每次一个属性更改时,useSelector都会渲染所有使用的组件。
这是减速机:
const initialState = {
productsDataState: [], // => this is populated by multiple objects
searchProducts: [],
isSearchOn: false,
inputValue: '',
listOrder: [],
toastify: ['green', ''],
toastifyOpen: false
}
const reducer = ((state = initialState, action) => {
switch (action.type) {
case actionTypes.UPDATE_PRODUCT:
return {
...state,
productsDataState: action.products,
listOrder: action.listOrder
}
case actionTypes.SET_TOASTIFY:
return {
...state,
toastify: action.toastify,
toastifyOpen: action.open
}
case actionTypes.SET_SEARCH:
return {
...state,
searchProducts: action.searchProducts,
isSearchOn: action.isSearchOn,
inputValue: action.inputValue …Run Code Online (Sandbox Code Playgroud) 在我的fullfilledi 中得到的响应为undefined。有人请帮忙吗?
代码 :
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const fetchPost = createAsyncThunk('fetch/post', async (params: string) => {
try {
const { data } = await axios.get('https://registry.npmjs.org/-/v1/search', { params: { text: params } })
data.objects.map((result: any) => {
console.log('result', result)//getting result
return result.package.name;
});
} catch (err: any) {
return err?.response;
}
})
interface RepositoriesState {
loading: boolean;
error: string | null;
data: string[];
}
const initialRepoState:RepositoriesState = {
loading: …Run Code Online (Sandbox Code Playgroud) 我使用“react-redux”:“^ 9.0.4”,“react-router-dom”:“^ 6.21.1”,“react-scripts”:“5.0.1”,“redux”:“^ 5.0。 0", "redux-thunk": "^3.1.0" 我想使用 React-Redux 在 React.js 中使用中间件创建登录,这是我的代码。
// src/middleware/store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const guard = createStore(rootReducer, applyMiddleware(thunk));
export default guard;
Run Code Online (Sandbox Code Playgroud)
// src/middleware/actions.js
import axios from 'axios';
export const login = (username, password, history) => async (dispatch) => {
try {
const response = await axios.post('https://xxx-api.xxx-xxxxxxx.com/users/login', {
username,
password,
});
dispatch({
type: 'LOGIN_SUCCESS',
payload: {
user: response.data.user,
},
});
localStorage.setItem('token', response.data.data.token);
history.push('/admin/dashboard');
} catch …Run Code Online (Sandbox Code Playgroud) 在redux中,当调度一个动作时,reducer将相应地更改状态,调用该动作的组件也可以访问该状态(由Provider通过props传递)。我对吗?
状态是访问组件中操作结果的唯一方法吗?(调用动作的组件)。
如何将回调函数传递给操作,然后使用该方法将结果发送回组件?
redux-thunk ×10
reactjs ×8
redux ×6
javascript ×3
react-redux ×3
react-native ×2
typescript ×2
react-hooks ×1
redux-saga ×1