Redux的基础配置
步骤1: 安装 redux 相关的包:
npm i redux react-redux redux-thunk redux-devtools-extension
步骤2: store 目录中分别创建:actions 和 reducers 文件夹、index.js 文件
步骤3: 在 store/index.js 中,创建 store 并导出
import { legacy_createStore, applyMiddleware } from "redux";
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from './reducers'
const middlewares = composeWithDevTools(applyMiddleware(thunk))
const store = legacy_createStore(rootReducer, middlewares)
export default store
步骤4: 创建 reducers/index.js 文件,创建 rootReducer 并导出
import { combineReducers } from 'redux'
import login from './login'
const rootReducer = combineReducers({
login
})
export default rootReducer
步骤5: 创建 reducers/login.js 文件,创建基础 login reducer 并导出
import { LOGIN } from "../actionType";
const initValue = {
token: "",
};
export default function login(state = initValue, action) {
switch (action.type) {
case LOGIN:
return { ...state, token: action.payload };
default:
return state;
}
}
步骤6: 在 src/index.js 中为 React 组件接入 Redux
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
步骤7: 在 actions/Login.js 中封装axios发请求
import request from '@/utils/request'
import { LOGIN } from '../actionType'
export const login = (payload) => {
return async (dispatch) => {
const res = await request({
method: 'post',
url: '/authorizations',
data: payload
})
dispatch({
type: LOGIN,
payload: res.data.token
})
}
}