Making AJAX requests in Redux is typically not done directly within Redux action creators. Instead, you will use middleware to handle asynchronous logic, most commonly with the redux-thunk middleware. Here is a basic example of making AJAX requests using redux-thunk and the fetch API:
- Install
redux-thunk:
shnpm install redux-thunk
- Configure the Store to Use
redux-thunkMiddleware:
javascriptimport { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; const store = createStore( rootReducer, applyMiddleware(thunk) );
- Create Action Creators:
javascript// Synchronous action for when the request starts const fetchDataRequest = () => ({ type: 'FETCH_DATA_REQUEST' }); // Synchronous action for when the request succeeds const fetchDataSuccess = (data) => ({ type: 'FETCH_DATA_SUCCESS', payload: data }); // Synchronous action for when the request fails const fetchDataFailure = (error) => ({ type: 'FETCH_DATA_FAILURE', payload: error }); // Asynchronous action creator using thunk middleware const fetchData = (url) => { return (dispatch) => { dispatch(fetchDataRequest()); fetch(url) .then(response => { if (!response.ok) { throw new Error(`Error status: ${response.status}`); } return response.json(); }) .then(json => { dispatch(fetchDataSuccess(json)); }) .catch(error => { dispatch(fetchDataFailure(error.message)); }); }; };
- Use the Asynchronous Action in a Component:
javascriptimport React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchData } from './actions'; const MyComponent = () => { const dispatch = useDispatch(); const data = useSelector(state => state.data); const isLoading = useSelector(state => state.isLoading); const error = useSelector(state => state.error); useEffect(() => { dispatch(fetchData('https://api.example.com/data')); }, [dispatch]); if (isLoading) { return <div>Loading...</div>; } if (error) { return <div>Error: {error}</div>; } return ( <div> {data && <pre>{JSON.stringify(data, null, 2)}</pre>} </div> ); }; export default MyComponent;
- Handle Actions in the Reducer:
javascriptconst initialState = { isLoading: false, data: [], error: null }; const dataReducer = (state = initialState, action) => { switch(action.type) { case 'FETCH_DATA_REQUEST': return { ...state, isLoading: true }; case 'FETCH_DATA_SUCCESS': return { ...state, isLoading: false, data: action.payload }; case 'FETCH_DATA_FAILURE': return { ...state, isLoading: false, error: action.payload }; default: return state; } }; export default dataReducer;
This is a simple example of a Redux asynchronous flow. In real applications, you may need more complex error handling, state updates, or the use of other middleware and libraries (such as redux-saga and axios). Additionally, Redux Toolkit simplifies many Redux setup steps, including configuring the store and writing reducers/action creators. You may want to consider using Redux Toolkit to further simplify your code.
2024年6月29日 12:07 回复