189 8069 5689

Redux-React代码原理分析

目标

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 = () => (
  
    
  
);

render(, 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 (
      

Counter

{this.props.count}
) } } //具体的属性转换函数 function mapStateToProps(state) { return { count: state.count }; } //通过connect方法将store的state属性转换成本组件的属性 export default connect(mapStateToProps)(Counter);

网页标题:Redux-React代码原理分析
文章源于:http://cdxtjz.cn/article/pogjjh.html

其他资讯