咱们实现一个最基本的点击按钮加减操做javascript
store/index.jsjava
import { createStore } from 'redux';
const countReducer = (state = 0, action) => {
const {type, payload} = action
switch(type) {
case 'ADD':
return state + payload;
case 'MINUS':
return state - payload;
default:
return state
}
}
const store = createStore(
countReducer
)
export default store;
复制代码
先建立一个storereact
ReduxPage.jsgit
import React, { Component } from 'react'
import store from '../store/'
export default class ReduxPage extends Component {
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
this.forceUpdate()
})
}
componentWillUnmount() {
if(this.unsubscribe) {
this.unsubscribe()
}
}
add = () => {
store.dispatch({type: 'ADD', payload: 1})
}
minus = () => {
store.dispatch({type: 'MINUS', payload: 1})
}
render() {
return(
<div> <h3>Reduxpage</h3> <p>{store.getState()}</p> <button onClick={this.add}>同步+</button> <button onClick={this.minus}>同步-</button> </div>
)
}
}
复制代码
好,咱们已经实现了redux。就是这么简单。上面的有个注意的地方,就是必定要在更新的时候进行监听,否则没法更新Dom的内容。github
咱们再回顾一下基本的流程:store里面有一个counterReducer,它是一个纯函数,传入的是state,返回的是新的state,里面定义了修改state的规则,而后把这个counterReducer注入到store里面,咱们就可使用store定义的一些方法干一些事情了。在ReduxPage.js里面,咱们用了store.getState()这个方法访问了state的值。当点击按钮的时候,咱们会经过store.dispatch触发一个ation,counterReducer收到这个action之后。会根据action的type,来执行相应的修改规则,而后对state做出更新,当state更新的时候,store.subscribe()会监听state的变化,而后经过this.forceUpdate()更新了Dom,这样,一个完整的redux就实现了它应该实现的功能。redux
下面进入源码,咱们去看看具体是怎么实现的异步
咱们须要实现一个createStore类,而后去实现它内部的几个方法函数
Jredux/createStore.jspost
export default function createStore(reducer) {
let currentState;
let currentlistenrs = [];
function getState() {
return currentState;
}
function dispatch(action) {
currentState = reducer(currentState, action)
currentlistenrs.forEach(listener => listener())
}
function subscribe(listener) {
currentlistenrs.push(listener)
return () => {
const index = currentlistenrs.indexOf(listener)
currentlistenrs.splice(index, 1)
}
}
// 初始化
dispatch({type: 'Jredux'});
return {
getState,
dispatch,
subscribe
}
}
复制代码
就这么简单,一个redux的源码就写完了,咱们用上面的这个代码也能够实现按钮加减的操做了。this