【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 Agent 基本理论与项目实战(一)
前端·react.js·前端框架
谢尔登7 小时前
10_从 React Hooks 本质看 useState
前端·ubuntu·react.js
辰同学ovo8 小时前
从全局登录状态管理学习 Redux
前端·javascript·学习·react.js
光影少年8 小时前
reeact虚拟DOM、Diff算法原理、key的作用与为什么不能用index
前端·react.js·掘金·金石计划
江南十四行9 小时前
ReAct Agent 基本理论与项目实战(二)
前端·react.js·前端框架
摘星编程10 小时前
当AI开始学会“使用工具“——从ReAct到MCP,大模型如何获得真正的行动力
前端·人工智能·react.js
啊哈一半醒12 小时前
React 核心知识点系统总结:从基础语法到高级 API,一篇文章梳理完整学习路线
javascript·学习·react.js
cn_mengbei2 天前
用React Native开发OpenHarmony应用:Reanimated共享元素过渡
javascript·react native·react.js
We་ct2 天前
React 性能优化精讲
前端·javascript·react.js·性能优化·前端框架·html·浏览器
光影少年2 天前
前端在页面渲染优化和组件优化经验?
前端·vue.js·react.js·前端框架