菜单

Redux计数器

2019年5月25日 - CSS/CSS3

Redux是1种缓和数量共享的方案

功能:计数器组件,每点击开关,展现数字加1
组件:
****一. UI组件:又称”纯组件”,由参数决定它的值。****
只担负 UI 的表现,不包括别的专门的学问逻辑。
从未动静(即不接纳this.state那么些变量)。
全部数据都由参数(this.props)提供。
不利用其余 Redux 的 API。
****二.容器组件:担负管理数据和逻辑****
肩负管理数据和事情逻辑,不担任 UI 的呈现
含蓄内部景色
使用 Redux 的 API
关键函数:
connect: 将那三种组件连起来。以下是三种组件。
(一) 输入逻辑:外部的数目(即state对象)怎么样转移为 UI 组件的参数
(二) 输出逻辑:用户爆发的动作如何形成 Action 对象,从 UI 组件传出去。
provide组件: 能够让容器组件得到state对象(外部的数额),才具生成 UI
组件的参数。那样provider包罗的全部子组件就暗中同意都能够拿到state了。

图片 1

import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'

// React component
class Counter extends Component {
  render() {
    //定义里面的两个函数value,onIncreaseClick
    const { value, onIncreaseClick } = this.props
    return (
    <div>
      //UI组件
      {value}
      //容器组件
      <button onClick={onIncreaseClick}>Increase</button>
    </div>
    )
  }
}
//counter中函数内的属性设置
Counter.propTypes = {
  value: PropTypes.number.isRequired,
  onIncreaseClick: PropTypes.func.isRequired
}

// Action
const increaseAction = { type: 'increase' }

// Reducer
function counter(state = { count: 0 }, action) {
  const count = state.count
  switch (action.type) {
    case 'increase':
      return { count: count + 1 }
    default:
      return state
   }
}

// Store
const store = createStore(counter)

// Map Redux state to component props
//value到state的映射 
function mapStateToProps(state) {
  return {
    value: state.count
  }
}
// Map Redux actions to component props
//onIncreaseClick到dispatch的映射
function mapDispatchToProps(dispatch) {
  return {
    onIncreaseClick: () => dispatch(increaseAction)
  }
}

// Connected Component
//将这输入逻辑与输出逻辑组件连接起来
const App = connect(
   mapStateToProps,
   mapDispatchToProps
)(Counter)

ReactDOM.render(
   <Provider store={store}>
     <App />
   </Provider>,
   document.getElementById('root')
)
import {createStore} from 'redux';
import React from 'react';
import ReactDOM from 'react-dom';
import {connect, createProvider} from 'react-redux'


// data
let allNum = {num :1000}

// 创建reducer, 名字的默认值为
function reducer(state, action) {
  let tmp = {}
  if (action.type == "decrease"){
    allNum.num = allNum.num - action.value;
    tmp = Object.assign({}, state, {num: allNum.num})
    return tmp
  }else if(action.type == "increase"){
    allNum.num = allNum.num + action.value;
    tmp = Object.assign({}, state, {num: allNum.num})
    return tmp
  }else{
    return state
  }
}

// 创建store存储数据(传入处理函数reducer, 核心数据allNum)
let store = createStore(reducer, allNum)
console.log("初始化的数据为",store.getState('num'))

// 添加监听函数
store.subscribe(() => {console.log("监听函数发出:", store.getState())});

// 发出action
let tmp = {};
tmp = store.dispatch({type: "decrease", value: 10})
console.log("---->", tmp);
tmp = store.dispatch({type: "decrease", value: 100})
console.log("---->", tmp);
tmp = store.dispatch({type: "increase", value: 31})
console.log("---->", tmp);
tmp = store.dispatch({type: "increase", value: 123})
console.log("---->", tmp);

class MyComponent extends React.Component {
 render() {return <div>Hello World</div>;}
}

ReactDOM.render(<MyComponent />, document.getElementById("root"));

React和Redux组合使用

React组件, 有五个数据集, props和state

props表示外部传入组件的参数(数据由外部传入, 能够被表面改造)

state代表组件固有的特性(数据私有, 不能被表面改造)

大家得以把多少个React组件的props交由Redux进行政管理制,
那样就贯彻了React组件之间数据的共享

图片 2

组件怎么样读写多少

零件通过action发送频域信号, reducer管理action, story内的值被reducer修改,
由于React组件已经被绑定到story中, 所以story内的数码被涂改后,
能够直接同步到React的机件中

图片 3

小案例: 实现3个重组计数器

单个计数器的数目由组件自个儿state管理

多个计数器的多少只和由Redux管理

图片 4

动图演示

落到实处的源码如下

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>react-webpack-demo</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

index.js

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import Redux from 'redux';
import { connect, Provider } from 'react-redux';
import { createStore } from 'redux';
import { PropTypes } from 'prop-types';

class ManageCounter extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return ( <div>
      <p className="title">计数器</p> 
      <Counter id = "0" />
      <Counter id = "1" />
      <Counter id = "2" />
      <p className="result"> 组件值的和为: { this.props.sum } </p> 
      </div> )
  }
}


class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.changeSum = this.changeSum.bind(this)
    this.decrease = this.decrease.bind(this)
    this.increase = this.increase.bind(this)
    this.state = { value: 0 };
  }
  changeSum() {
    this.props.dispatch({ type: 'changeSum', payload: { id: this.props.id, value: this.state.value } })
  }
  decrease() {
    let self = this;
    this.setState({ value: this.state.value - 1 }, () => {
      self.changeSum()

    })
  }

  increase() {
    let self = this;
    self.setState({ value: this.state.value + 1 }, () => {
      self.changeSum()
    })
  }

  render() {
    const { value } = this.state;
    let { id } = this.props;
    return ( <div >
      <input type = "button"value = "减1" onClick = { this.decrease }/> 
       { value } < /span><br/ >
      <input type = "button" value = "加1" onClick = { this.increase }/>
      </div> )
  }
}

// 创建reducer
function reducer(state = { number: [0, 0, 0], sum: 0 }, action = {}) {
  if (action.type == 'changeSum') {
    let { id, value } = action.payload
    console.log("id:", id, "value:", value);
    state.number[id] = value
    let tmpSum = 0;
    for (let i = 0; i < state.number.length; i++) {
      tmpSum += state.number[i]
    }
    return Object.assign({}, state, { sum: tmpSum });
  } else {
    return state;
  }
}

const CounterMapStateToProps = (state) => ({

})

const ManageCounterMapStateToProps = (state) => ({
  sum: state.sum
})

const mapDispatchToProps = (dispatch) => ({
  dispatch: dispatch
})


// 创建store
let store = createStore(reducer)
// connect连接
Counter = connect(CounterMapStateToProps, mapDispatchToProps)(Counter)
ManageCounter = connect(ManageCounterMapStateToProps, mapDispatchToProps)(ManageCounter)

ReactDOM.render(
  <Provider store = { store }>
  <ManageCounter />
  </Provider> ,
  document.getElementById('root'));

index.scss

$designWidth: 750;
@function px2rem($px) {
  @return $px*10/$designWidth+rem;
}

#root {
  div {
    p {
      font-size: px2rem(300);
      color: #5EA1F3;
      text-align: center;
    }
    div {
      font-size: px2rem(500);
      display: flex;
      color: #64B587;
      border: 1px solid #F0BB40;
      input {
        flex: 1 1 auto;
        background-color: #64B587;
        font-size: px2rem(200);
        outline: none;
        color:#ffffff;
      }
      span {
        width: 300px;
        flex: 1 1 auto;
        text-align: center;
      }
    }
    .title {
      color: #BDBDBD;
    }
    .result {

      font-size: px2rem(200);
    }
  }
}

小结

redux的设计观念是很简短的, 也许有了很干练的库函数供大家调用,
所以面前蒙受3个主题素材时, 我们着想的爱戴是:
React组件内什么数据要求被Redux管理?把第叁难题思虑清楚,
难题也就一蹴而就了诸多!

以上正是本文的全体内容,希望对我们的上学抱有补助,也意在大家多多辅助脚本之家。

您恐怕感兴趣的小说:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图