国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Redux實現組合計數器的示例代碼

2019-11-19 13:33:41
字體:
來源:轉載
供稿:網友

Redux是一種解決數據共享的方案

import {createStore} from 'redux';import React from 'react';import ReactDOM from 'react-dom';import {connect, createProvider} from 'react-redux'// datalet 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())});// 發出actionlet 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組件之間數據的共享

組件如何讀寫數據

組件通過action發送信號, reducer處理action, story內的值被reducer修改, 由于React組件已經被綁定到story中, 所以story內的數據被修改后, 可以直接同步到React的組件中

小案例: 實現一個組合計數器

單個計數器的數據由組件自身state管理

三個計數器的數據只和由Redux管理

動圖演示

實現的源碼如下

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 }/>       <span > { value } < /span><br/ >      <input type = "button" value = "加1" onClick = { this.increase }/>      </div> )  }}// 創建reducerfunction 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})// 創建storelet 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的設計思想是很簡單的, 也有了很成熟的庫函數供我們調用, 所以面對一個問題時, 我們考慮的重點是: React組件內哪些數據需要被Redux管理?把重點問題考慮清楚, 問題也就解決了大半!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 尉氏县| 基隆市| 疏附县| 红安县| 红河县| 贺兰县| 广安市| 定日县| 湖北省| 阿鲁科尔沁旗| 贡觉县| 政和县| 夏津县| 灌云县| 佛学| 临猗县| 乐山市| 洛宁县| 拉萨市| 吉安市| 民乐县| 双桥区| 赤壁市| 文化| 龙州县| 堆龙德庆县| 齐河县| 都昌县| 浦县| 清水县| 聂拉木县| 丰原市| 新民市| 甘肃省| 密云县| 孟州市| 甘泉县| 阿勒泰市| 兴文县| 璧山县| 曲周县|