在Redux中拒绝Fetch Promise可以通过使用Redux中间件来实现。Redux中间件是一个函数,它可以在action被发起之后,到达reducer之前拦截并处理action。下面是一个示例:
npm install redux-thunk
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export const fetchData = () => {
return dispatch => {
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Fetch failed');
}
return response.json();
})
.then(data => {
dispatch({ type: 'FETCH_SUCCESS', payload: data });
})
.catch(error => {
dispatch({ type: 'FETCH_FAILURE', payload: error.message });
});
};
};
在上面的示例中,我们使用fetch函数来进行异步请求,并在请求成功或失败时分别派发不同的action。
const initialState = {
data: null,
error: null
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return {
...state,
data: action.payload,
error: null
};
case 'FETCH_FAILURE':
return {
...state,
data: null,
error: action.payload
};
default:
return state;
}
};
在上面的示例中,我们根据不同的action类型更新state中的数据。
通过以上步骤,我们就可以在Redux中拒绝Fetch Promise。当Fetch请求失败时,会派发一个FETCH_FAILURE的action,从而更新state中的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云