在配置多个API请求的Redux reducer时,可以按照以下步骤进行:
createStore
函数来创建store,并将所有的reducer传递给它。例如:import { createStore, combineReducers } from 'redux';
import reducer1 from './reducer1';
import reducer2 from './reducer2';
const rootReducer = combineReducers({
reducer1,
reducer2,
});
const store = createStore(rootReducer);
// reducer1.js
const initialState = {
data: [],
loading: false,
error: null,
};
const reducer1 = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_DATA_REQUEST':
return {
...state,
loading: true,
error: null,
};
case 'FETCH_DATA_SUCCESS':
return {
...state,
loading: false,
data: action.payload,
};
case 'FETCH_DATA_FAILURE':
return {
...state,
loading: false,
error: action.payload,
};
default:
return state;
}
};
export default reducer1;
// reducer2.js
const initialState = {
data: {},
loading: false,
error: null,
};
const reducer2 = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_DETAILS_REQUEST':
return {
...state,
loading: true,
error: null,
};
case 'FETCH_DETAILS_SUCCESS':
return {
...state,
loading: false,
data: action.payload,
};
case 'FETCH_DETAILS_FAILURE':
return {
...state,
loading: false,
error: action.payload,
};
default:
return state;
}
};
export default reducer2;
dispatch
函数来触发相应的action。例如:import axios from 'axios';
const fetchData = () => {
return (dispatch) => {
dispatch({ type: 'FETCH_DATA_REQUEST' });
axios.get('/api/data')
.then((response) => {
dispatch({ type: 'FETCH_DATA_SUCCESS', payload: response.data });
})
.catch((error) => {
dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
});
};
};
const fetchDetails = () => {
return (dispatch) => {
dispatch({ type: 'FETCH_DETAILS_REQUEST' });
axios.get('/api/details')
.then((response) => {
dispatch({ type: 'FETCH_DETAILS_SUCCESS', payload: response.data });
})
.catch((error) => {
dispatch({ type: 'FETCH_DETAILS_FAILURE', payload: error.message });
});
};
};
connect
函数来连接组件和Redux store,并通过mapStateToProps
函数将需要的state映射到组件的props中。例如:import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchData, fetchDetails } from './actions';
const MyComponent = ({ data, loading, error, fetchData, fetchDetails }) => {
useEffect(() => {
fetchData();
fetchDetails();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
<h1>Data: {data}</h1>
</div>
);
};
const mapStateToProps = (state) => ({
data: state.reducer1.data,
loading: state.reducer1.loading,
error: state.reducer1.error,
});
export default connect(mapStateToProps, { fetchData, fetchDetails })(MyComponent);
这样,就可以配置多个API请求的Redux reducer,并在应用中使用它们了。请注意,上述代码仅为示例,实际情况中可能需要根据具体需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云