Redux-小案例-加一操做

初次學習redux,熟悉ianyigew數字加 1 的小案例react

App.js文件redux

import React from 'react';
import store from './store/index'
console.log()
class App extends React.Component {
    constructor(){
        super()
        this.state = {
            msg : 'HELLO REDUX',
            num: store.getState().num
        }
        this.handleAdd = this.handleAdd.bind(this)
        store.subscribe(this.upstateNum.bind(this))
    }
    render(){
        let {msg,num} = this.state
        return (
            <div className="App">
                <h1>{msg}</h1>
                <h2>{num}</h2>
                <button className="btn" onClick={this.handleAdd.bind(this)}>加 1 操做</button>
            </div>
        );
    }
    handleAdd(){
        console.log("加 1 操做")
        store.dispatch({
            type:'addNum'
        })
    }
    // j堅挺倉庫中的數據發生改變後,將指賦給組建的state
    upstateNum(){
        this.setState({
            num:store.getState().num
        })
    }
}

export default App;

 

store目錄下index.js文件函數

建立一個倉庫createS透熱(),該函數接受一個參數,參數也是一個函數reducer學習

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

export default store

 

store目錄下reducer.js文件this

const initState = {
    num : 10
}

const reducer = (state = initState,action)=>{
    switch(action.type){
        case "addNum":
            let numState = JSON.parse(JSON.stringify(state))
            numState.num++
            return numState
    }
    return state
}

export default reducer
相關文章
相關標籤/搜索