前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react-redux实践

react-redux实践

作者头像
用户6094182
发布2019-08-23 17:41:33
8870
发布2019-08-23 17:41:33
举报
文章被收录于专栏:joealzhoujoealzhou

react-redux实践

了解

1、什么是redux

官方解释:redux 是 js 应用的可预测状态的容器。 可以理解为全局数据状态管理工具(状态管理机),用来做组件通信等。

2、为什么使用redux

90a9e69d3675d26d70dd270708d442188b3.jpg

当没有使用redux时兄弟组件间传值将很麻烦,代码很复杂冗余。使用redux定义全局单一的数据Store,可以自定义Store里面存放哪些数据,整个数据结构也是自己清楚的。

3、state

前端中的state就是数据,就是一个对象。redux中的state是不能直接修改的,只能通过action来修改,相当于我们在单例中定义setter方法。

4、action

redux 将每一个更改动作描述为一个action,要更改state中的内容,你需要发送action。一个action是一个简单的对象,用来描述state发生了什么变更。

代码语言:javascript
复制
const INCREMENT = 'INCREMENT'
const incrementAction = {"type": INCREMENT, "count": 2}

上面这就是一个action,说白了就是一个对象,根据里面的type判断做什么操作。

5、reducer

数据state,指示action都有了那么就是实现了。reducer就是根据action来对state进行操作。

代码语言:javascript
复制
const calculate = (state: ReduxState = initData, action: Action ) => {
    switch (action.type) {
        case INCREMENT:
            return {num: state.num + action.count}
        case REDUCE:
            return {num: state.num - action.count}
        default:
            return state
    }
}

export {calculate}

通过reducer操作后返回一个新的state,比如这里根据action的type分别对state.num进行加减。

6、store

store就是整个项目保存数据的地方,并且只能有一个。创建store就是把所有reducer给它。

代码语言:javascript
复制
import { createStore, combineReducers } from "redux";
import { calculate } from "./calculate";

// 全局你可以创建多个reducer 在这里统一在一起
const rootReducers = combineReducers({calculate})
// 全局就管理一个store
export const store = createStore(rootReducers)
7、dispatch

store.dispatch()是组件发出action的唯一方法。

代码语言:javascript
复制
store.dispatch(incrementAction);

通过store调用incrementAction,那么就直接把store里的数据修改了。

一、创建项目、添加依赖

  • 创建项目
代码语言:javascript
复制
$ yarn create react-app redux-demo --typescript
  • 添加redux
代码语言:javascript
复制
$ yarn add redux react-redux @types/react-redux @types/redux
  • 添加路由
代码语言:javascript
复制
$ npm install --save react-router-dom

需要注意的是还需要配置一下tsconfig.json,创建tsconfig.paths.json否则编译报错。可以拷贝示例项目中的两个文件。下面为示例中的主要代码,写了一个简单加减修改数据。

屏幕快照 2019-07-18 14.43.34.png

二、核心代码

代码语言:javascript
复制
<!--pages/home/index.tsx-->
import React, { Component } from 'react';
import './index.css'
import { incrementAction, reduceAction } from '../reducers/calculate';
import { connect } from 'react-redux';

<!--定义Home的属性-->
interface Props {
    num: number,
    increment: ()=>any,
    decrement: ()=>any,
}

<!--从全局state中拿数据设置到Home的props-->
const mapStateToProps = (state: any) => {
    return {
      num: state.calculate.num
    };
  };
  
  const mapDispatchToProps = (dispatch: any) => ({
    increment: () => dispatch(incrementAction),
    decrement: () => dispatch(reduceAction)
  });
  
<!--组件链接到redux的store-->
@(connect( mapStateToProps, mapDispatchToProps, ) as any)
export default class Home extends Component<Props, any> {
    render() {
        return <div className='container'>
            <p onClick={this.props.increment}>click to increment num</p>
            <p onClick={this.props.decrement}>click to decrement num</p>
            <p>{this.props.num}</p>
        </div>
    }
}

一个store可以添加多个reducer,比如这里是一个加减的reducer,你还可以分文件创建其它的操作,便于分类管理。只要创建store的时候使用combineReducers全部绑定到一起就可以了。

代码语言:javascript
复制
<!--这里是实现加减的reducer-->
export const INCREMENT = "INCREMENT"
export const REDUCE = "REDUCE"

export const incrementAction = {type: INCREMENT, count: 2}
export const reduceAction = {type: REDUCE, count: 1}

interface ReduxState {
    num: number
}

interface Action {
    type: string,
    count:  number,
}

const initData = {
    num: 0
}

const calculate = (state: ReduxState = initData, action: Action ) => {
    switch (action.type) {
        case INCREMENT:
            return {num: state.num + action.count}
        case REDUCE:
            return {num: state.num - action.count}
        default:
            return state
    }
}

export {calculate}

三、示例代码

github链接

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.07.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • react-redux实践
    • 了解
      • 1、什么是redux
      • 2、为什么使用redux
      • 3、state
      • 4、action
      • 5、reducer
      • 6、store
      • 7、dispatch
    • 一、创建项目、添加依赖
      • 二、核心代码
        • 三、示例代码
        相关产品与服务
        容器服务
        腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档