Redux-React 代码原理分析

发布时间:2020-05-17 18:38:56 作者:sendoffice
来源:网络 阅读:276

目标

react使用redux的主要目的是:
1)实现简洁统一的状态维护,提高代码可维护性;
2)实现简洁的注入依赖,避免重重传递参数;
Plug Any Data Into Any Component. This is the problem that Redux solves. It gives components direct access to the data they need.
3)实现自动化渲染。

index.js

应用的入口代码

import React from 'react';
import { render } from 'react-dom';
import Counter from './Counter';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

const initialState = {
  count: 0
};

function reducer(state = initialState, action) {
  switch(action.type) {
    case 'INCREMENT':
      return {
        count: state.count + 1
      };
    case 'DECREMENT':
      return {
        count: state.count - 1
      };
    default:
      return state;
  }
}

/**
* 1) 创建全局存储对象 store,传入合适的reducer.
*/
const store = createStore(reducer);

/**
* 2) 将store实例绑定到 App
*/

const App = () => (
  <Provider store={store}>
    <Counter/>
  </Provider>
);

render(<App />, document.getElementById('root'));

组件代码

import React from 'react';
import { connect } from 'react-redux';

/**
* index.js创建的store全局对象,会注入到所有下级对象中,因此这里才可以使用dispatch函数来改变属性。
*/
class Counter extends React.Component {
  increment = () => {
    //实际上是调用全局store对象的dispatch函数
    this.props.dispatch({ type: 'INCREMENT' });
  }

  decrement = () => {
    this.props.dispatch({ type: 'DECREMENT' });
  }

  render() {
    return (
      <div>
        <h3>Counter</h3>
        <div>
          <button onClick={this.decrement}>-</button>
          <span>{this.props.count}</span>
          <button onClick={this.increment}>+</button>
        </div>
      </div>
    )
  }
}

//具体的属性转换函数
function mapStateToProps(state) {
  return {
    count: state.count
  };
}

//通过connect方法将store的state属性转换成本组件的属性
export default connect(mapStateToProps)(Counter);
推荐阅读:
  1. vue和react指的是什么框架
  2. hook如何正确的在react中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react redux ct

上一篇:百度糯米猴年初一夺冠  协同创新三大法器赢得漂亮

下一篇:对权限管理页面控制知识

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》