问题
在多模块文件的React应用中,如果在根模块中创建 Redux store,然后通过props依次传递给所有的子组件,实在太麻烦了
方案
react-redux模块可用于使用了Redux的React项目中,提供了两方面的扩展功能
① 一个“Context.Provider”:为它所包含的所有子组件提供store使用
② 一个HOC高阶组件函数:connect()函数将自定义组件提升为“高阶组件”,将Redux的dispatch和state映射为被包装组件的props
步骤
① 安装依赖模块 npm i redux react-redux
② 顶级组件中创建 store 和 reducer,使用Provider为子组件共享store
③ 将store.dispatch()映射为子组件的props
④ 将store.getState()映射为子组件的props
@index
import React from "react";
import ReactDOM from "react-dom/client";
import { createStore } from "redux";
import CartShow from "./components/CartShow";
import CartModify from "./components/CartModify";
import { Provider } from "react-redux";
// state
let initState = {
buyCount: 5,
};
// action
// {type:"ENCREASE"}
// {type:"DECREASE"}
// reducer
function appReducer(state = initState, action) {
console.log("state updated");
if (action.type === "ENCREASE") {
return { ...state, buyCount: state.buyCount + 1 };
} else if (action.type === "DECREASE") {
let buyCount = state.buyCount - 1;
buyCount = buyCount < 0 ? 0 : buyCount;
return { ...state, buyCount };
} else {
return state;
}
}
// store
let store = createStore(appReducer);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<CartShow></CartShow>
<hr />
<CartModify></CartModify>
</Provider>
);
components\CartShow.js
import React from "react";
import { connect } from "react-redux";
function CartShow(props) {
return <div>当前数量:{props.bc}</div>;
}
function mapStateToProps(state) {
return {
bc: state.buyCount,
};
}
export default connect(mapStateToProps, null)(CartShow);
@components\CartModify.js
import React from "react";
import { connect } from "react-redux";
function CartModify(props) {
return (
<div>
<button onClick={props.dec}>-</button>
<button onClick={props.enc}>+</button>
</div>
);
}
function mapDispathToProps(dispatch) {
return {
enc: () => {
dispatch({ type: "ENCREASE" });
},
dec: () => {
dispatch({ type: "DECREASE" });
},
};
}
export default connect(null, mapDispathToProps)(CartModify);