Redux狀態管理6Redux調試工具

使用 react-redux

  1. 老趙 雖然能力 很強,但是用起來比較麻煩 ,爲了方便管理,使用魏和尚來 負責 鏈接
  2. cnpm i –save react-redux
  3. 忘記 subscribe ,記住 reducer action dispatch
  4. React-redux 提供了 2個接口 ,Provider , connect 提供 鏈接的 功能

react-redux 的具體使用

  1. Provider 組件應該在最外層,傳入store 即可,只用一次.
  2. connect 負責從外部獲取組件需要的參數
  3. Connect 可以用裝飾起的方式來寫

Index.js

import React from "react"
import ReactDom from "react-dom"
import { createStore , applyMiddleware ,compose } from "redux"
import thunk from "redux-thunk"
import { Provider } from "react-redux"
import App from "./App"
import { counter} from "./index.redux"

const store = createStore(counter,
    compose(applyMiddleware(thunk),
        window.devToolsExtension?window.devToolsExtension():f=>f))


ReactDom.render(
    (<Provider store = {store}>
        <App />
    </Provider>),
    document.getElementById("root")
    )


App.js

import React from "react"
import { Button } from "antd-mobile"
import {connect} from "react-redux"
import {addGun,ReduceGun,FakerGun,addGunAsync} from "./index.redux"
class App extends React.Component{
    // constructor(props){
    //     super(props);
    // }
    render(){
        return(
            <div>
                <Button type="primary" >現在有機槍{this.props.num}把</Button>
                <Button type="primary"  onClick={this.props.addGun}>申請武器</Button>
                <Button type="primary"  onClick={this.props.ReduceGun}>收繳武器</Button>
                <Button type="primary"  onClick={this.props.FakerGun}>搶武器</Button>
                <Button type="primary"  onClick={ this.props.addGunAsync }>拖2秒</Button>

            </div>
        )
    }
}

const mapStatetoProps = (state)=>{
    return {num:state}
}

const actionCreaters = {addGun,ReduceGun,FakerGun,addGunAsync}

App = connect(mapStatetoProps,actionCreaters)(App)
export default App

Index.redux.js



const ADD_GUN = "加機關槍"
const REMOVE_GUN = "減機關槍"
const FAKE_GUN = "搶機關槍"


/*reducer*/
export function counter (state=0,action){
    switch(action.type){
        case ADD_GUN:
            return state + 1
        case REMOVE_GUN:
            return state - 1
        case FAKE_GUN:
            return state * 10
        default:
            return 10
    }
}

export function addGun(){
    return {type:ADD_GUN}
}

export function ReduceGun(){
    return {type:REMOVE_GUN}
}

export function FakerGun(){
    return {type:FAKE_GUN}
}

export function addGunAsync(){
    return dispatch=>{
        setTimeout(()=>{dispatch(addGun())},500)
    }
}










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章