Giter Club home page Giter Club logo

kredux's Introduction

redux

基本用法

  • 通过createStore创建store
  • 在创建store时需传入纯函数reducer
  • reducer接收两个参数:stateaction
  • 在需要用到redux的组件中引入store
  • 编写改变状态的方法,通过store.dispatch()方法来派发action
  • 被派发的action会转发给reducerreducer会通过action来更新state
  • 组件可以通过store.getState()方法来获取状态
  • 通过store.subscribe()方法来订阅state的更新,每次状态改变都会触发回调事件

用到redux的组件

import React, { Component } from 'react'
import store from "../store"

export class ReduxPage extends Component {
  componentDidMount() {
    store.subscribe(() => {
      this.forceUpdate()
    })
  }
  add = () => {
    store.dispatch({type: "ADD", payload: 100})
  }
  
  render() {
    return (
      <div>
        <h3>ReduxPage</h3>
        <div>{store.getState()}</div>
        <button onClick={this.add}>add</button>
      </div>
    )
  }
}

export default ReduxPage

创建storereducer

import { createStore } from "../kredux";

const reducer = (state = 0, { type, payload }) => {
  switch (type) {
    case "ADD":
      return state + payload
    default:
      return state
  }
};

const store = createStore(reducer);

export default store;

kredux's People

Contributors

lwrench avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.