【taro react】---- 【使用 redux 的配置笔记】

【taro react】---- 【使用 redux 的配置笔记】

1. 目标

  1. 学会 yarn 或 npm 安装中间件
  2. 学会配置 redux 的 store
  3. 学会 store 的接入和使用

2. 安装中间件

安装redux用到的中间件: redux react-redux redux-thunk redux-logger

ruby 复制代码
$ yarn add redux react-redux redux-thunk redux-logger
# 或者使用 npm
$ npm install --save redux react-redux redux-thunk redux-logger

3. 配置 store

在项目 src 目录下新增一个 store 目录,在目录下增加 index.js 文件用来配置 store。

  1. src/store/index.js
javascript 复制代码
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducer from '../reducers';

// window.__REDUX_DEVTOOLS_EXTENSION__  可使用Redux DevTools插件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

// 使用Redux-thunk中间件
const enhancer = composeEnhancers(applyMiddleware(thunk));

// 创建store
const store = createStore(reducer, enhancer);

export default store;

4. 接入 store

在项目入口文件 app.js 中使用 redux 中提供的 Provider 组件将前面写好的 store 接入应用。

  1. src/app.js
scala 复制代码
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import store from './store'
import './app.css'

class App extends Component {
  // 在 App 类中的 render() 函数没有实际作用
  // 请勿修改此函数
  render () {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}

export default App

5. 开始使用

  1. constants 目录,用来放置所有的 action type 常量
  2. actions 目录,用来放置所有的 actions
  3. reducers 目录,用来放置所有的 reducers

5.1 以官方示例,开发一个简单的加、减计数器功能

新增 action type

  1. src/constants/counter.js
arduino 复制代码
export const ADD = 'ADD'
export const MINUS = 'MINUS'

5.2 新增 reducer 处理

  1. src/reducers/counter.js
dart 复制代码
import { ADD, MINUS } from '../constants/counter'

const INITIAL_STATE = {
  num: 0
}

export default function counter (state = INITIAL_STATE, action) {
  switch (action.type) {
    case ADD:
      return {
        ...state,
        num: state.num + 1
      }
    case MINUS:
      return {
        ...state,
        num: state.num - 1
      }
    default:
      return state
  }
}
  1. src/reducers/index.js
javascript 复制代码
import { combineReducers } from 'redux'
import counter from './counter'
import { defaultIndex } from './defaultIndex'
import { commonCart } from './commonCart'
import { goodsDetail } from './goodsDetail'

export default combineReducers({
  counter,
  defaultIndex,
  commonCart,
  goodsDetail 
})

5.3 新增 action 处理

  1. src/actions/counter.js
javascript 复制代码
import {
  ADD,
  MINUS
} from '../constants/counter'

export const add = () => {
  return {
    type: ADD
  }
}
export const minus = () => {
  return {
    type: MINUS
  }
}

// 异步的 action
export function asyncAdd () {
  return dispatch => {
    setTimeout(() => {
      dispatch(add())
    }, 2000)
  }
}

6. 页面或组件使用

在页面(或者组件)中进行使用,我们将通过 redux 提供的 connect 方法将 redux 与我们的页面进行连接。

  1. src/pages/index/index.js
typescript 复制代码
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { View, Button, Text } from '@tarojs/components'

import { add, minus, asyncAdd } from '../../actions/counter'

import './index.css'


@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  add () {
    dispatch(add())
  },
  dec () {
    dispatch(minus())
  },
  asyncAdd () {
    dispatch(asyncAdd())
  }
}))
class Index extends Component {
  render () {
    return (
      <View className='index'>
        <Button className='add_btn' onClick={this.props.add}>+</Button>
        <Button className='dec_btn' onClick={this.props.dec}>-</Button>
        <Button className='dec_btn' onClick={this.props.asyncAdd}>async</Button>
        <View><Text>{this.props.counter.num}</Text></View>
        <View><Text>Hello, World</Text></View>
      </View>
    )
  }
}

export default Index

7. 注意

  1. connect 方法接受两个参数 mapStateToProps 与 mapDispatchToProps
  2. mapStateToProps,函数类型,接受最新的 state 作为参数,用于将 state 映射到组件的 props
  3. mapDispatchToProps,函数类型,接收 dispatch() 方法并返回期望注入到展示组件的 props 中的回调方法

8. 官方文档

使用 Redux

本文基本都是按照官方文档一步一步配置,仅作为开发记录,有问题,请反馈联系!

相关推荐
海海思思4 小时前
React 虚拟列表中的 Hook 使用陷阱
react.js
车前端11 小时前
React 18 核心新特性解析
react.js
小公主13 小时前
React + ECharts 数据可视化实战与面试要点
react.js·echarts
鹏多多13 小时前
React状态管理库Zustand的实用教程
前端·javascript·react.js
江城开朗的豌豆13 小时前
useLayoutEffect:你以为它和useEffect是"亲兄弟"?其实差别大了!
前端·javascript·react.js
江城开朗的豌豆13 小时前
聊聊useEffect:谁说副作用不能“优雅”?
前端·javascript·react.js
无羡仙1 天前
React 状态更新:如何避免为嵌套数据写一长串 ...?
前端·react.js
EndingCoder1 天前
React 19 与 Next.js:利用最新 React 功能
前端·javascript·后端·react.js·前端框架·全栈·next.js
sorryhc1 天前
【AI解读源码系列】ant design mobile——CapsuleTabs胶囊选项卡
前端·javascript·react.js
林太白1 天前
Vite+React+ts项目搭建(十分钟搭建个最新版React19项目吧)
前端·后端·react.js