[英]Why is this createAsyncThunk behaving strangely?
我對來自 redux 工具包 API 的這個createAsyncThunk
有一些問題
export const getPayments = createAsyncThunk('getPayments/all', async ({ rejectWithValue }) => {
try {
const response = await fetch(`/payments`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
})
console.log('res:', response)
return response
} catch (e) {
console.log('ERROR:', e)
rejectWithValue(e)
}
})
每當我添加rejectWithValue
作為參數時,它總是在 redux devtools 中顯示為已拒絕。 當我刪除它時,它總是會完成。 這里發生了什么? 如果fetch出錯,我只想在下面調用這個function? 為什么它總是拒絕它?
編輯:我看到這個Cannot destructure property 'rejectWithValue' of 'undefined' as it is undefined.
在現在的回應中,這就是為什么它總是被拒絕是有道理的,為什么會發生這種情況,我該如何解決?
這是一個如何做到這一點的示例,如評論所述, 有效載荷創建者的rejectWithValue
是第二個參數的屬性,有效載荷創建者需要返回rejectWithValue
調用的結果,這是一個示例:
// toggle reject
const reject = ((shouldReject) => () =>
(shouldReject = !shouldReject))(true);
// test thunk action creator
const testAsyncThunk = createAsyncThunk(
'some/test',
// arg is the argument passed to the action creator, can be ignored if not used
async (arg, { rejectWithValue }) => {
console.log('argument passed to action creator:', arg);
if (reject()) {
//return result of rejectWithValue call
return rejectWithValue('rejected');
}
return Promise.resolve('resolved');
}
);
當您發送使用createAsyncThunk
創建的 thunk 時,生成的 promise 將不會拒絕,除非您使用unwrapResult
。
這是一個演示行為的最小應用程序:
import React from 'react';
import ReactDOM from 'react-dom';
import {
createAsyncThunk,
unwrapResult,
} from '@reduxjs/toolkit';
import { Provider, useDispatch } from 'react-redux';
import {
createStore,
applyMiddleware,
compose,
} from 'redux';
// toggle reject
const reject = ((shouldReject) => () =>
(shouldReject = !shouldReject))(true);
// test thunk action creator
const testAsyncThunk = createAsyncThunk(
'some/test',
// arg is the argument passed to the action creator, can be ignored if not used
async (arg, { rejectWithValue }) => {
console.log('argument passed to action creator:', arg);
if (reject()) {
//return result of rejectWithValue call
return rejectWithValue('rejected value');
}
return Promise.resolve('resolved value');
}
);
const reducer = (state, { type, payload }) => {
return state;
};
//creating store with redux devtools and thunk middleware
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,
{},
composeEnhancers(
applyMiddleware(
({ dispatch, getState }) => (next) => (action) =>
//minimal implementation of thunk middleware
typeof action === 'function'
? action(dispatch, getState)
: next(action)
)
)
);
const App = () => {
const dispatch = useDispatch();
return (
<button
onClick={() =>
dispatch(testAsyncThunk('argument passed'))
.then(
(resolved) => {
console.log('action resolved with', resolved);
return resolved;
},
(rejected) =>
// this never executes because promise returned
// by dispatch(tunkaction) will not reject
console.log('action rejected with:', rejected)
)
.then(
//after unwrap result you have a promise that will
// reject
unwrapResult
)
.catch((err) =>
console.log('rejected with...', err)
)
}
>
dispatch action
</button>
);
};
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.