Redux基本使用

本文介绍了Redux的状态管理机制,包括基本思路如store、action和reducer的概念,以及如何创建和使用store。详细讲解了如何单独使用Redux,配合react-redux进行React应用的状态管理,还提到了redux-devtools的使用以及如何在项目中配置和使用修饰器进行连接。
摘要由CSDN通过智能技术生成

目录

简介

redux 基本思路

redux 基本使用

单独使用 redux

配合 react-redux 使用

redux-devtools

使用修饰器


简介

本文介绍 redux 的使用方法。

主要包括以下几个部分

  • redux 基本思路
  • 单独使用 redux
  • 配合 react-redux 使用
  • redux-devtools
  • 使用修饰器

redux 基本思路

        ·redux 是用来管理公共状态,公共 state 都存放在 store 中。使用 createStore() 方法新建一个 store

        ·直接修改容易引起误操作,需要有条件的操作 store ,不能直接修改

        ·使用 store.getState() 来获取 state

        ·使用 store.dispatch(action) 修改 state

        ·使用 store.subscribe(listener) 实现监听,如果有改动,进行对应的响应操作

        ·action 是一个对象,基本格式 { type: TEST, payload: { name: 'ddd' } }

        ·action creator 是 action 生成函数,根据传入的参数生成对应的 action

redux 基本使用

  • redux 安装命令:npm i redux --save
  • 新建 reducer 文件
// action type
const COUNT_ADD = "数量增加"
const COUNT_MINUS = "数量减少"

// initial state
const initState = {
  test: 'test'
  count: 10
}

// reducer
export default function(state = initState, action) {
  switch(action.type) {
    case COUNT_ADD:
      return {
        ...state,
        count: state.count + 1
      }
    case COUNT_MINUS:
      return {
        ...state,
        count: state.count - 1
      }
    default:
      return state
  }
}

// action creator
export function countAdd() {
  return { type: COUNT_ADD }
}
export function countMinus() {
  return { type: COUNT_MINUS }
}
  • 如果有多个 reducer ,可以使用 combineReducers 方法将多个 reducer 合并成一个
import { combineReducers } from 'redux'

import app from './app'
import user from './user'

export default combineReducers({ app, user })
  • 使用 createStore 生成 store
import { createStore } from 'redux'
import rootReducer from './reducers'
export default createStore(rootReducer)

// 使用中间件
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers'
export default createStore(rootReducer, applyMiddleware(thunk))

单独使用 redux

const init = store.getState()
console.log(init)

function listener() {
  const { count } = store.getState()
  console.log(`目前计数为:${count}`)
}
store.subscribe(listener)

// 派发事件
store.dispatch(countAdd())
store.dispatch(countAdd())
store.dispatch(countMinus())

配合 react-redux 使用

  • 在 react 项目中一般配合 react-redux 使用
  • react-redux 安装命令:npm i react-redux --save
  • react-redux 提供了 Provider ,该组件将 store 放到 context 中,方便子孙组件直接使用 store
  • react-redux 提供了 connect(mapStateToProps, mapDispatchToProps) 用来将对应的 state 和 dispatch 放到组件的 props 下
// ...
import { Provider } from 'react-redux'
import store from './store'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
import React from 'react'
import { connect } from 'react-redux'
import { countAdd, countMinus } from '../../store/reducers/app'
import { WingBlank, WhiteSpace,Button } from 'antd-mobile'

class Demo extends React.Component {
  render() {
    return (
      <WingBlank style={{marginTop: 50}}>
        <p>目前计数:{this.props.count}</p>
        <WhiteSpace />
        <Button type="warning" onClick={this.props.countAdd}>+1</Button>
        <WhiteSpace />
        <Button type="primary" onClick={this.props.countMinus}>-1</Button>
      </WingBlank>
    )
  }
}
export default connect(
  ({ app }) => app,
  { countAdd, countMinus }
)(Demo)

备注

  • connect 高级组件处理之后,在 props 中就有对应的 state 和 action 了
  • connect 的第一个参数是将 state 转为 props 的方法 mapStateToProps ,当然也可以直接传对象
  • connect 的第二个参数是将 dispatch 转为 props 的方法 mapDispatchToProps ,当然也可以直接传对象

redux-devtools

redux-devtools 是谷歌浏览器的插件,方便调试

需要在代码中打开

// 没有中间件时开启devToolsExtension
import { createStore } from 'redux'
import rootReducer from './reducers'
export default createStore(rootReducer, window.devToolsExtension ? window.devToolsExtension() : f=>f)

// 使用中间件并开启devToolsExtension
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers'
export default createStore(rootReducer, compose(
  applyMiddleware(thunk),
  window.devToolsExtension ? window.devToolsExtension() : f=>f
))

使用修饰器

修饰器相关知识参考:装饰器模式(Decorator模式)理解、使用

create-react-app 项目为例:

  • 如果 babel 版本低于 7.x ,需要下载babel-plugin-transform-decorators-legacy 
npm i babel-plugin-transform-decorators-legacy --save
  • 修改 package.json 文件
{
  // ...
  "babel": {
    // ...
    "plugins": [
      "transform-decorators-legacy"
      // ...
    ]
  },
  // ...
}
  • 如果是 babel 7.x 及以上版本,需要下载 @babel/plugin-proposal-decorators 
npm i @babel/plugin-proposal-decorators --save
  • 修改 package.json 文件
{
  // ...
  "babel": {
    // ...
    "plugins": [
      // ...
      ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ]
  },
  // ...
}
  • 在组件中 connect 就可以使用修饰器格式了。其他的,比如 withRouter 都可以用修饰器格式
// ...
@connect(
  ({ test }) => ({ count: test.count}),
  { testCountAdd }
)
class Demo extends React.Component {
  // ...
}
export default Demo
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chengbo_eva

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值