react狀態(tài)異步操作redux-thunk

接著上一篇redux的基本使用摆舟,我們接著實現(xiàn)狀態(tài)管理的異步操作,畢竟實際開發(fā)中接口獲取的動態(tài)數(shù)據(jù)占大多數(shù)。
首先我們來進行安裝

npm install redux-thunk redux-logger -S 或
cnpm install redux-thunk redux-logger -S 或
yarn add redux-thunk redux-logger -S 或

順便安裝了一個redux的日志輸出框架恨诱,前面講過一篇基于node的日志框架媳瞪。大家感興趣的可以去看看。

基于上一篇的代碼結(jié)構(gòu)照宝,我們這次稍微做一些重構(gòu)蛇受,讓代碼層次更清晰一些。
首先在src/store文件夾下面建一個login-redux.js文件厕鹃,放入如下代碼

login-redux.js

export const loginReducer = (state="登錄", action) => {
    switch(action.type){
        case "nologin":
            return "登錄"
        case "nowlogin":
            return "登錄中...."
        case "haslogin":
            return "已登錄"
        case "logout" :
            return "退出登錄"
        default :
            return state
    }
}
//action creator
export const nowlogin = () =>({type: "nowlogin"})
export const haslogin = () =>({type: "haslogin"})
export const logout = () =>({type: "logout"})

store/index.js

import { createStore, applyMiddleware } from "redux"
import {loginReducer} from "./login-redux"
const store = createStore(loginReducer)
export default store;

src/reduxdeom.js

import React from "react"
import { connect } from "react-redux"
import { nowlogin, haslogin, logout } from "./store/login-redux"
const mapStateToProps = state => ({status: state});
const mapDispatchToProps = {nowlogin, haslogin, logout, asyncLogin}
@connect(mapStateToProps, mapDispatchToProps)
class Reduxdemo extends React.Component{
    render(){
        const { status, nowlogin, haslogin, logout } = this.props;
        return (
            <div>
                <p>用react-redux改造后</p>
                <p>{status}</p>
                <button onClick={nowlogin}>去登陸=&gt;登錄中</button><br/><br/>
                <button onClick={haslogin}>登錄中=&gt;登陸成功</button><br/><br/>
                <button onClick={logout}>退出</button>
            </div>
        )
    }
}
export default Reduxdemo

以上便重構(gòu)完成龙巨,下面開始異步操作
在src/store/login-redux.js中添加如下代碼

export const asyncLogin  = () => dispatch =>{
    dispatch({type: "nowlogin"});
    setTimeout(() => {dispatch({type: "haslogin"})}, 1500)
}

src/reduxdeom.js

import React from "react"
import { connect } from "react-redux"
import { nowlogin, haslogin, logout, asyncLogin } from "./store/login-redux"
const mapStateToProps = state => ({status: state});
const mapDispatchToProps = {nowlogin, haslogin, logout, asyncLogin}

@connect(mapStateToProps, mapDispatchToProps)
class Reduxdemo extends React.Component{
    render(){
        const { status, nowlogin, haslogin, logout, asyncLogin } = this.props;
        return (
            <div>
                <p>用react-redux改造后</p>
                <p>{status}</p>
                //增加一個從開始登陸->登錄中->登錄成功的按鈕
                <button onClick={asyncLogin}>登錄=&gt;登陸成功</button><br/><br/>
                <button onClick={nowlogin}>去登陸=&gt;登錄中</button><br/><br/>
                <button onClick={haslogin}>登錄中=&gt;登陸成功</button><br/><br/>
                <button onClick={logout}>退出</button>
            </div>
        )
    }
}
export default Reduxdemo

src/index.js

import { createStore, applyMiddleware } from "redux" //applyMiddleware 用來執(zhí)行中間鍵
import logger from "redux-logger"
import thunk from "redux-thunk"
import {loginReducer} from "./login-redux"
const store = createStore(loginReducer, applyMiddleware(logger, thunk));//注意參數(shù)寫入順序,先執(zhí)行l(wèi)ogger再執(zhí)行thunk
export default store;

啟動項目


3.gif

操作多個redux模塊

接下來我們來看看如果有多個reducer的情況熊响,我們在store目錄下創(chuàng)建一個count-redux.js文件實現(xiàn)一個簡單地加一減一的實例旨别。

src/store/count-redux.js

export function countRedux(state=0, action){
    switch(action.type){
        case "add":
            return state + 1
        case "minus":
            return state - 1 
        default: 
        return  state
    }
}

export const add = () => ({type: "add"})
export const minus = () => ({type: "minus"})

src/store/index.js中引入

import { createStore, applyMiddleware, combineReducers } from "redux"  //combineReducers 用來合并多個reducer模塊
import logger from "redux-logger"
import thunk from "redux-thunk"
import {loginReducer} from "./login-redux"
import {countRedux} from "./count-redux"

const store = createStore(combineReducers({
   //分別給每個模塊取一個別名
    count: countRedux,
    login: loginReducer
}), applyMiddleware(logger, thunk))

export default store;

src/reduxdemo.js增加加一減一功能

import React from "react"
import { connect } from "react-redux"
import { nowlogin, haslogin, logout, asyncLogin } from "./store/login-redux"
import { add, minus } from "./store/count-redux"  //引入action
//取值時有了變化要加上剛才取的別名
const mapStateToProps = state => ({status: state.login, num: state.count});
const mapDispatchToProps = {nowlogin, haslogin, logout, asyncLogin, add, minus}

@connect(mapStateToProps, mapDispatchToProps)
class Reduxdemo extends React.Component{
    render(){
        const { status, nowlogin, haslogin, logout, asyncLogin, add, minus, num } = this.props;
        return (
            <div>
                <div>
                    <p>用react-redux改造后</p>
                    <p>{status}</p>
                    <button onClick={asyncLogin}>登錄=&gt;登陸成功</button><br/><br/>
                    <button onClick={nowlogin}>去登陸=&gt;登錄中</button><br/><br/>
                    <button onClick={haslogin}>登錄中=&gt;登陸成功</button><br/><br/>
                    <button onClick={logout}>退出</button>
                </div>
                <div>
                    <p>{num}</p>
                    <button onClick={add}>加一</button>
                    <button onClick={minus}>減一</button>
                </div>
            </div>
        )
    }
}
export default Reduxdemo

啟動項目


1.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市汗茄,隨后出現(xiàn)的幾起案子秸弛,更是在濱河造成了極大的恐慌,老刑警劉巖洪碳,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件递览,死亡現(xiàn)場離奇詭異,居然都是意外死亡瞳腌,警方通過查閱死者的電腦和手機绞铃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來嫂侍,“玉大人儿捧,你說我怎么就攤上這事√舫瑁” “怎么了菲盾?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長各淀。 經(jīng)常有香客問我懒鉴,道長,這世上最難降的妖魔是什么碎浇? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任临谱,我火速辦了婚禮,結(jié)果婚禮上奴璃,老公的妹妹穿的比我還像新娘悉默。我一直安慰自己,他們只是感情好溺健,可當我...
    茶點故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布麦牺。 她就那樣靜靜地躺著钮蛛,像睡著了一般。 火紅的嫁衣襯著肌膚如雪剖膳。 梳的紋絲不亂的頭發(fā)上魏颓,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天,我揣著相機與錄音吱晒,去河邊找鬼甸饱。 笑死,一個胖子當著我的面吹牛仑濒,可吹牛的內(nèi)容都是我干的叹话。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼墩瞳,長吁一口氣:“原來是場噩夢啊……” “哼驼壶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起喉酌,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤热凹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后泪电,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體般妙,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年相速,在試婚紗的時候發(fā)現(xiàn)自己被綠了碟渺。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡突诬,死狀恐怖苫拍,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情攒霹,我是刑警寧澤怯疤,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站催束,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏伏社。R本人自食惡果不足惜抠刺,卻給世界環(huán)境...
    茶點故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望摘昌。 院中可真熱鬧速妖,春花似錦、人聲如沸聪黎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至锦秒,卻和暖如春露泊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背旅择。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工惭笑, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人生真。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓沉噩,卻偏偏與公主長得像,于是被迫代替她去往敵國和親柱蟀。 傳聞我的和親對象是個殘疾皇子川蒙,可洞房花燭夜當晚...
    茶點故事閱讀 44,647評論 2 354