第一步
安装 redux 相关的包:yarn add redux react-redux redux-thunk redux-devtools-extension axios
第二步
在 store 目录中分别创建:actions 和 reducers 文件夹、index.js 文件
/store
/actions
login.js
index.js
/reducers
login.js
index.js
index.js
//store index.js
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducers' //状态
import thunk from 'redux-thunk' //中间件
import { composeWithDevTools } from 'redux-devtools-extension'
const middlewares = composeWithDevTools(applyMiddleware(thunk))
const store = createStore(rootReducer, middlewares)
export default store
//store/actions/index.js
//引入所有模块
export * from "./login";
export * from "./user";
export * from "./article";
//store/actions/login.js
import axios from "axios";
import { setToken ,clearToken} from "@/utils";
export const login = (mobile, code) => {
return async (dispatch) => {
const res = await axios.post(
"http://geek.itheima.net/v1_0/authorizations",
{
mobile,
code,
}
);
const { token } = res.data.data;
dispatch({ type: "login/token", payload: token });
setToken(token);
};
};
export const logout = () => {
return (dispatch,getState)=>{
clearToken()
dispatch({type : 'login/logout'})
dispatch({type : 'user/logout'})
}
}
//store/reducers/index.js
import { combineReducers } from 'redux'
import login from './login'
//模块化
const rootReducer = combineReducers({
login
})
export default rootReducer
//store/reducers/login.js
// 状态默认值为:''
const initialState = '';
const login = (state = initialState, action) => {
switch (action.type) {
case "login/token":
return action.payload;
case "login/logout":
return initialState;
default:
return state;
}
};
export default login
//根文件/index.js 相当于main.js文件
//必须引入
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.querSelector('#root')
)
获取值
import store from '@/store'
console.log(store.getState());
import { useSelector } from 'react-redux'
// 比如,Redux 中的状态是个对象,就可以:
const list = useSelector(state => state.list)
使用 Redux 的套路: 组件 dispatch 异步 action -> 提供异步 action -> 完成异步操作 -> 继续 dispatch 普通 action 来发起状态更新 -> reducers 处理状态更新