redux

 

reducer.jscss

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.jsreact

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

store.jsredux

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

export default store;

action.jsapp

import store from './store';
let incAction = ()=>{
    let act =  {
        type:'INC'
    }
    //store 分發給reducer的action做爲參數
    store.dispatch(act);
}
export {
    incAction 
}

 app.jssvg

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;
相關文章
相關標籤/搜索