【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

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

相关推荐
小白白一枚1113 小时前
vue和react的框架原理
前端·vue.js·react.js
星空下的曙光6 小时前
React 虚拟 DOM Diff 算法详解,Vue、Snabbdom 与 React 算法对比
vue.js·算法·react.js
生活不易,被迫卖艺6 小时前
Redux与React-环境准备(React快速上手1)
前端·javascript·react.js
wordbaby10 小时前
React 异步请求数据处理优化经验总结
前端·react.js
超级土豆粉11 小时前
Taro Hooks 完整分类详解
前端·javascript·react.js·taro
中等生11 小时前
为什么现在的前端项目都要'启动'?新手必懂的开发环境变迁
前端·javascript·react.js
小高00713 小时前
🚀React 更新界面全流程:从 setState 到 像素上屏
前端·react.js·面试
不如吃茶去14 小时前
开源推荐:LocalSqueeze - 隐私优先的本地图片压缩工具
前端·react.js·electron
Ratten14 小时前
【taro react】 ---- Stepper 步进器组件封装
react.js
CodeCraft Studio16 小时前
DHTMLX重磅发布React Scheduler组件,赋能日程管理开发!
前端·react.js·前端框架·dhtmlx·调度·scheduler·排程