React-Redux 老版本 connext的使用记录(只为记录)

注:新版 redux 用法中 使用useSelector、useDispatch替代connect,这里只做老用法的记录使用。
​Redux最新用法参考 个人React专栏react初级学习

React-Redux是一个用于将React应用程序连接到Redux状态管理器的库。以下是React-Redux的简单用法示例:

  1. 安装React-Redux库
npm install react-redux
  1. 创建Redux store

创建Redux store,这是存储应用程序状态的地方。可以使用Redux createStore函数创建store。

import { createStore } from 'redux';

const initialState = {
  count: 0
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1
      };
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1
      };
    default:
      return state;
  }
};

const store = createStore(reducer);
  1. 创建React组件

创建一个React组件,将组件中需要的store中的状态传递给组件的props。可以使用React Redux提供的connect函数将组件连接到Redux store并订阅state更改。

import React from 'react';
import { connect } from 'react-redux';

const Counter = ({ count, increment, decrement }) => (
  <div>
    <h1>Count: {count}</h1>
    <button onClick={increment}>Increment</button>
    <button onClick={decrement}>Decrement</button>
  </div>
);

const mapStateToProps = state => ({
  count: state.count
});

const mapDispatchToProps = {
  increment: () => ({ type: 'INCREMENT' }),
  decrement: () => ({ type: 'DECREMENT' })
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值