redux

reducer.js

import _state from './state'
let reducer =  (state=_state,action)=>{ //纯函数
    // state数据
    // action 处理方式方法 是一个对象 他是act
    let newState = {...state}; //深拷贝对象 得到副本 进行修改
    if(action.type==='INC'){
        // newState.n ++;
        newState = {...newState,n:_state.n++}
    }
    return newState;

}
export default reducer;

state.js

const state = {
    n:6
}
export default state;

store.js

import {createStore} from 'redux';
import reducer from './reducer'
const store = createStore(reducer);

export default store;

action.js

import store from './store';
let incAction = ()=>{
    let act =  {
        type:'INC'
    }
    //store 分发给reducer的action作为参数
    store.dispatch(act);
}
export {
    incAction 
}

 app.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import store from './redux/store'
//引入redux import {incAction } from './redux/action'
//引入redux方法 console.log(store) class App extends Component { constructor(props){ super(props); this.state = { n:store.getState().n
     //获取store里面的n } store.subscribe(()
=>{ //只要数据变化了这个回调函数就会执行 this.setState({ n:store.getState().n }) }) this.inc = this.inc.bind(this); } inc(){ console.log(incAction) incAction() } render() { return ( <div className="App" onClick={this.inc}> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> { this.state.n} <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
原文地址:https://www.cnblogs.com/l8l8/p/9476960.html