讲解版本
"redux": "^4.2.0",
"react-redux": "^8.0.5",
配置
import RouterApp from "./router/index.js";
import store from "./store";
import { Provider } from "react-redux";
export default function App() {
return (
<Provider store={store}>
<RouterApp />
</Provider>
);
}
import { reducer } from "../reducer";
import { createStore } from "redux";
export default createStore(reducer);
const initStore = {
phone: "admin",
pass: "123",
};
exports.reducer = (store = initStore, action) => {
switch (action.type) {
case "addUser":
return {
phone: (store.name = action.value.username),
pass: (store.name = action.value.password),
};
default:
return store;
}
};
import { connect } from "react-redux";
function Login(props) {
console.log(props);
}
const getStore = (state) => {
return state;
};
export default connect(getStore)(Login);
import { connect } from "react-redux";
function Register(props) {
props.addUser(values);
}
const setStore = (dispacth) => {
return {
addUser: (value) => {
dispacth({
type: "addUser",
value,
});
},
};
};
export default connect(null, setStore)(Register);
描述过程
- 下载redux以及react-redux
- 新建reducer文件,配置操作仓库方法以及仓库初始化
- 新建store文件,引入createStore,连接reducer
- 可在mian.js中通过react-redux中的 Provider 传递 store
- 使用通过connect 配置连接 =>形式:connect(得到store的方法, 设置store的方法)(UI)