react-redux的基本使用

react-redux

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);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值