• redux进行研究3


    1. 需要⼀个store来存储数据
    2. store⾥的reducer初始化state并定义state修改规则
    3. 通过dispatch⼀个action来提交对数据的修改
    4. action提交到reducer函数⾥,根据传⼊的action的type,返回新的
    state
    创建store,src/store/ReduxStore.js
     
    import {createStore} from 'redux'
    const counterReducer = (state = 0, action) => {
    switch (action.type) {
    case 'add':
    return state + 1
    case 'minus':
    return state - 1
    default:
    return state
    }
    }
    const store = createStore(counterReducer)
     
    export default store
    创建ReduxPage
    import React, { Component } from "react";
    import store from "../store/ReduxStore";
    export default class ReduxPage extends Component {
    componentDidMount() {
    store.subscribe(() => {
    console.log("subscribe");
    this.forceUpdate();
    //this.setState({});
    });
    }
    add = () => {
    store.dispatch({ type: "add" });
    };
    minus = () => {
    store.dispatch({ type: "minus" });
    };
    stayStatic = () => {
    store.dispatch({ type: "others" });
    };
    render() {
    console.log("store", store);
    return (
    <div>
    <h1>ReduxPage</h1>
    <p>{store.getState()}</p>
    <button onClick={this.add}>add</button>
    <button onClick={this.minus}>minus</button>
    <button onClick={this.stayStatic}>static</button>
    </div>
    );
    }
    }
    如果点击按钮不能更新,因为没有订阅状态变更
    还可以在src/index.js的render⾥订阅状态变更
     
    import store from './store/ReduxStore'
    const render = ()=>{
    ReactDom.render(
    <App/>,
    document.querySelector('#root')
    )
    }
    render()
    store.subscribe(render)
    检查点
    1. createStore 创建store
    2. reducer 初始化、修改状态函数
    3. getState 获取状态值
    4. dispatch 提交更新
    5. subscribe 变更订阅
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    Spring MVC Introduction
    整理的一些文档
    Spring MVC: Some notes
    诡异的 "Error 45 initializing SQL*Plus Internal error"
    Buggy Buggy "NULL"
    【zz】贝叶斯推断及其互联网应用
    Node.js安装,配置npm源(指定仓库和指定源)
    通过命令给安装完成的oracle服务端创建用户并授权
    PLSQL 设置浏览器对象窗口文件颜色、排列顺序(对象窗口Table、Packages等文件夹颜色,顺序)
    搭建初始化vue项目
  • 原文地址:https://www.cnblogs.com/zhouyideboke/p/13215356.html
Copyright © 2020-2023  润新知