1. 程式人生 > 其它 >Redux管理狀態的簡單應用,存取state

Redux管理狀態的簡單應用,存取state

技術標籤:React

1、首先新建store資料夾,在裡面引入redux

import { createStore } from 'redux';

const reducer = (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT': return state + 1;
        case 'DECREMENT': return state > 0 ? state - 1 : state;
        default: return state;
    }
};

const store = createStore(reducer);

export default store;

2、在具體的頁面中引入store

import React,{Component} from 'react'
import './login.scss'
import store from '../../store'  //引入狀態物件

class Login extends Component{
    constructor(props) {
        super(props);
        this.state = {
            count: store.getState() //獲取狀態資料
        }
        store.subscribe(() => {   //監聽狀態變化更新資料
            this.setState({
                count:store.getState()
            })
        })
    }
    onIncrement = () => {  //分發狀態更新  存state
        store.dispatch({
            type:'INCREMENT'
        })
    }

    onDecrement = () => { //分發狀態更新 存state
        store.dispatch({
            type: 'DECREMENT'
        })
    }
    render() {
        return (
            <div className="P-login">
                {/*//取state*/}
                <h1>{this.state.count}</h1>
                <button onClick={this.onIncrement}>+</button>
                <button onClick={this.onDecrement}>-</button>
            </div>
        )
    }
}
export default Login

效果: