redux-saga HellWorld入门 异步计数器(react-redux)

前端之家收集整理的这篇文章主要介绍了redux-saga HellWorld入门 异步计数器(react-redux)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

点击加减按钮,延迟1秒操作加减动作(模拟异步网络请求)
最终调用Action “Done” 将结果展示

import React from 'react'
import ReactDOM from 'react-dom'
import {createStore,applyMiddleware} from 'redux'
import {Provider,connect} from 'react-redux'
import createSagaMiddleware,{takeEvery} from 'redux-saga'


import {put,fork} from 'redux-saga/effects'
function reducers(state=0,action) {
    switch (action.type) {
        case 'Done':
            return state + action.payload;
        default:
            return state;
    }
};


export function* AddAsync() {
    yield new Promise(function (resolve) {
        setTimeout(function () {
            resolve()
        },1000)
    })
    yield put({type: 'Done',payload: 1})
}

export function* SubAsync() {
    yield new Promise(function (resolve) {
        setTimeout(function () {
            resolve()
        },payload: -1})
}

function* watchIncrementAsync() {
    yield* takeEvery('ADD',AddAsync)
}

function* watchDecrementAsync() {
    yield* takeEvery('SUB',SubAsync)
}

var sagaMiddleware = createSagaMiddleware();
const store = createStore(reducers,applyMiddleware(sagaMiddleware))
function* root() {
    yield [
        fork(watchDecrementAsync),fork(watchIncrementAsync)
    ]
}

sagaMiddleware.run(root)

const ResultIn = (props) => <div>结果:{props.value}</div>

const Result = connect(
    mapStateToPropsResult
)(ResultIn)

var AppIn = (props) => <div>

    <span onClick={() => {
        props.onChangeAdd()
    }}>点我加1</span>

    <span onClick={() => {
        props.onChangeSub()
    }}>点我减1</span>


    <Result/></div>

function mapStateToPropsResult(state) {
    return {
        value: state
    }
}

function mapStateToProps(state) {
    return {
        value: state
    }
}

function mapDispatchToProps(dispatch) {
    return {
        onChangeAdd: () => {

            dispatch({type: 'ADD',payload: 1});
        },onChangeSub: () => {
            dispatch({type: 'SUB',payload: 1});
        }
    }
}

const App = connect(
    mapStateToProps,mapDispatchToProps
)(AppIn)

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

猜你在找的React相关文章