react-redux
react官方出的一个操作redux的库,更加方便舒服的在react项目中使用redux
react-redux的基本使用流程
// 创建容器层 container/count/index.js
// 使用 connnect 来连接UI层和容器层
// ui 组件
import CountUi from "../../components/Count/index";
import { increment } from "../../redux/count_actions";
//使用connect 将 ui组件和 容器组件连接
import { connect } from "react-redux";
const mapStateToProps = (state) => {
return {
count: state,
};
};
const mapDiapatchToProps = (dispatch) => {
return {
jia: (number) => dispatch(increment(number)),
};
};
// !!! 注意 connect 方法的使用
export default connect(mapStateToProps, mapDiapatchToProps)(CountUi);
// 将原来引入<Count /> 组件的地方换成 容器组件
// 将 store 以props 的形式传入
import React from "react";
import Count from "./containers/count";
import store from "./redux/store";
function App() {
return (
<>
<Count store={store} />
</>
);
}
export default App;
// count UI 组件中 使用 props 的形式来使用
function Count(props) {
console.log("props", props);
const mincrement = () => {
props.jia(100);
};
return (
<>
<div>Count is {props.count}</div>
<button onClick={mincrement}>+</button>
</>
);
}
react-redux 的优化
不必将容器层和ui层分开写了,写到一个文件即可
// components/count/index
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import {
increment,
decrement,
asyncIncrement,
} from "../../redux/count_actions";
function Count(props) {
console.log("props", props);
const mincrement = () => {
props.jia(100);
};
const mdecrement = () => {
props.jian(20);
};
const masyncIncrement = () => {
props.asyncJia(30, 1000);
};
return (
<>
<div>Count is {props.count}</div>
<button onClick={mincrement}>+</button>
<button onClick={mdecrement}>-</button>
<button onClick={masyncIncrement}>async+</button>
</>
);
}
export default connect(
(state) => ({ count: state }),
// (dispatch) => ({
// jia: (number) => dispatch(increment(number)),
// jian: (number) => dispatch(decrement(number)),
// asyncJia: (num, time) => dispatch(asyncIncrement(num, time)),
// })
//简写优化: react-redux 自动帮我们进行了dispatch 分发动作。
{
jia: increment,
jian: decrement,
asyncJia: asyncIncrement,
}
)(Count);