美文网首页
Redux简述

Redux简述

作者: EickL | 来源:发表于2019-06-10 20:43 被阅读0次

什么是 Redux?

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

## 为什么使用 Redux?

下面的图是不使用 Redux 和使用 Redux 时 父子组件之间的通信方式 image

可以看到,没用使用 Redux 的情况,如果两个互不相干的组件之间的需要通信的话,可能需要多个中间组件为他们进行消息传递,这样浪费资源,代码也会变得复杂。

Redux 中以单一数据源 Store 来存储状态数据,所有的状态都是可预测的(也就是说,所有的状态都是我们自己定义的)

设计思想

  • web 应用是一个状态机,视图与状态是一一对应的。
  • 所有的状态,保存在一个对象里面。

概念

state

redux 把每一个状态state(数据)都看作一个对象,这里的计数器,我们作为初始值,例如计数器的状态:

const initHomeState = { num: 0 };

这个对象就像一个“模型”,除了没有 setter。这样代码的不同部分不能任意改变状态,导致难以重现的错误。

action

redux 将每一个更改动作描述为一个action,要更改state中的内容,你需要发送action。一个action是一个简单的对象,用来描述state发生了什么变更,例如计数器的action分为递增和递减,代码如下:

// 递增
const incrementAction = { type: COUNTER_INCREMENT };
// 递减
const decrementAction = { type: COUNTER_DECREMENT };

如果状态发生了变化,我们就知道它为什么会改变。

reducer

我们需要将stateaction联系起来,为此我们写了一个叫reducer的函数。reducerstateaction作为参数,并返回应用的一个新的state,例如计数器的reducer

const counter = (
  state: { num: number } = initHomeState,
  action: { type: string }
) => {
  switch (action.type) {
    case COUNTER_INCREMENT:
      return Object.assign({}, state, { num: ++state.num });
    case COUNTER_DECREMENT:
      return Object.assign({}, state, { num: --state.num });
    default:
      return state;
  }
};

接下来,我们需要写一个rootReducer来管理应用的完整状态,需要使用combineReducers来结合reducer

import { combineReducers } from "redux";
​
const rootReducer = combineReducers({
  counter
});

store

store就是 redux 保存状态state(数据)的地方,可以看作一个容器,整个应用中只能有一个store,创建 store 需要传递reducer,通常会传递rootReducer

import { createStore } from "redux";
const store = createStore(rootReducer);

store.dispatch()

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

dispatch发出的action会传递到reducer中去,通过reducer返回下一个state

store.dispatch(incrementAction);
store.dispatch(decrementAction);

简单来说就是组件通过使用dispatch发送actionreducer来改变state从而改变组件的props,更新vdom,最后更新真实dom

redux 和 react native 组件的连接

我们需要安装 redux,react-redux:

yarn add redux react-redux @types/react-redux @types/redux

react-redux 的 API

connect()

connect()用来将 react 组件连接到 redux 的store,就是使 react 组件可以接收到store中的数据。

connect()的参数

  1. mapStateToProps?: Function
  2. mapDispatchToProps?: Function | Object
  3. mergeProps?: Function
  4. options?: Object

mapStateToProps?: (state, ownProps?) => Object

这个方法是用来指定 react 组件将使用哪些store中的数据,也就是说,当store中的state更新后,这个方法会接收state(方法的第一个参数),将state中变更的值通过返回值传递给 react 组件的props。例如计数器的mapStateToProps

const mapStateToProps = (state: any) => {
  return {
    num: state.counter.num
  };
};

mapDispatchToProps?: Object | (dispatch, ownProps?) => Object

这个方法的第一个参数就是store.dispatch,可以定义发送action的方法,并且将方法通过返回值传递给 react 组件的props。例如计数器的mapDispatchToProps

const mapDispatchToProps = (dispatch: any) => ({
  increment: () => dispatch(incrementAction),
  decrement: () => dispatch(decrementAction)
});

mergeProps?: (stateProps, dispatchProps, ownProps) => Object

这个方法用来生成 react 组件最终的props。一般情况下很少使用。

options?: Object

同样很少使用,可以点这里来查看官方文档

使用

然后需要为计数器按钮组件Counter建立连接

let Counter = ({ increment, decrement, num }) => (
  <View style={{ flex: 1 }}>
    <View style={{ flex: 1, textAlign: "center", paddingTop: "50%" }}>
      <Text style={{ fontSize: 30, textAlign: "center" }}>{num}</Text>
    </View>
    <View style={{ flex: 2 }}>
      <Button onPress={increment}>递增</Button>
      <Button onPress={decrement}>递减</Button>
    </View>
  </View>
);
const mapStateToProps = (state: any) => {
  return {
    num: state.counter.num
  };
};
const mapDispatchToProps = (dispatch: any) => ({
  increment: () => dispatch(incrementAction),
  decrement: () => dispatch(decrementAction)
});
Counter = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter);

react native的根组件(通常是 App 组件,App.tsx)使用react-redux提供的Provider组件设置全局store

import React, { Component } from "react";
import { Provider } from "react-redux";
import { connect } from "react-redux";
​
export default class App extends Component<Props> {
  render() {
    return (
      // 设置全局store
      <Provider store={store}>
        <Counter />
      </Provider>
    );
  }
}

接下来就可以点击递增按钮,来始store.counter.num进行递增了,递减也是可以的。

相关文章

  • Redux简述

    什么是 Redux? 官方解释:redux 是 js 应用的可预测状态的容器。 可以理解为全局数据状态管理工具(状...

  • 简述 Redux

    redux:解决数据传递问题,把所有数据放在store中传递。 1.基于react什么时候要用redux reac...

  • react + react-redux + iron-redux

    简述 搭建基于redux、react-redux、iron-redux的脚手架,此demo仅做个人练习使用。Hom...

  • redux一些事

    简述redux redux已经用的比较熟了,实际上redux并没有想象中那么复杂,就像redux官方文档说的没有黑...

  • react学习笔记-Redux入门(6)

    5-1、Redux概念简述 Redux = Reducer + Flux(2013官方推荐的数据存储插件)imag...

  • Redux思想简述

    数据流是我们的行为和响应的抽象(例如用户的点击,以及对应页面的更新) 单向数据流有助于明确具体的行为和对应的响应,...

  • 06.Redux入门

    Redux概念简述 Redux的工作流程 使用Antd实现TodoList页面布局 这里,我们新建一个项目1.cm...

  • redux-saga源码解读

    简述 redux-saga是用于维护redux异步操作的状态的一个中间件实现,其中reducer负责处理state...

  • 【Redux】—基本认知

    一、简述 1.定义:Redux是JavaScript状态容器,提供可预测化的状态管理。 2.设计动机: 解决,当J...

  • Redux源码阅读(一)——createStore、dispat

    简述 目的 Redux是一个用于更好地在组件外部管理状态的东西。通过使用它,我们可以轻松地更新或者获取state而...

网友评论

      本文标题:Redux简述

      本文链接:https://www.haomeiwen.com/subject/wnwtfctx.html