要在Redux中使用axios并自定义标题,你可以按照以下步骤进行操作:
npm install axios redux-thunk
api.js
,并添加以下代码:import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Custom-Header': 'Your Custom Header Value',
},
});
export default api;
在上面的代码中,我们创建了一个新的axios实例api
,并设置了baseURL和自定义标题。
userActions.js
,并添加以下代码:import api from './api';
export const fetchUser = () => {
return (dispatch) => {
dispatch({ type: 'FETCH_USER_REQUEST' });
api.get('/users')
.then((response) => {
dispatch({ type: 'FETCH_USER_SUCCESS', payload: response.data });
})
.catch((error) => {
dispatch({ type: 'FETCH_USER_FAILURE', payload: error.message });
});
};
};
在上面的代码中,我们使用api
实例发送了一个GET请求到/users
路径,并根据请求的结果分发相应的Redux action。
userReducer.js
,并添加以下代码:const initialState = {
isLoading: false,
users: [],
error: null,
};
const userReducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_USER_REQUEST':
return {
...state,
isLoading: true,
};
case 'FETCH_USER_SUCCESS':
return {
...state,
isLoading: false,
users: action.payload,
};
case 'FETCH_USER_FAILURE':
return {
...state,
isLoading: false,
error: action.payload,
};
default:
return state;
}
};
export default userReducer;
在上面的代码中,我们定义了一个初始状态initialState
,并根据action的类型更新了Redux的状态。
store.js
,并添加以下代码:import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import userReducer from './userReducer';
const store = createStore(userReducer, applyMiddleware(thunk));
export default store;
在上面的代码中,我们创建了Redux store,并将userReducer
和redux-thunk
中间件应用于store。
Provider
组件将store传递给应用程序。例如,在你的根组件文件中添加以下代码:import React from 'react';
import { Provider } from 'react-redux';
import store from './redux/store';
const App = () => {
return (
{/* Your App component */}
);
};
export default App;
通过上述步骤,你可以在Redux中使用axios并自定义标题来发送请求。确保根据你的实际情况修改代码中的URL、action类型和redux状态等部分。