zoukankan      html  css  js  c++  java
  • 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 变更订阅
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    React Native 开发豆瓣评分(三)集成 Redux
    React Native 开发豆瓣评分(二)路由配置
    React Native 开发豆瓣评分(一)环境搭建&配置模拟器
    VSCode 搭建 React Native 环境
    webpack4 + ejs 构建多页应用
    react-native 沉浸式状态栏
    react-native——tab配置及跳转
    uni-app 入门之 nvue (weex) 爬坑记
    javascript中bind()、call()、apply()的使用
    mysql数据库中文乱码配置文件解决以及常见mysql命令
  • 原文地址:https://www.cnblogs.com/zhouyideboke/p/13215356.html
Copyright © 2011-2022 走看看