import React, { Component } from "react";
import { Text, View, Button } from "react-native";
import { createStore, applyMiddleware } from "redux";
import { Provider, connect } from "react-redux";
import { put, takeEvery, delay, call } from 'redux-saga/effects'
import createSagaMiddleware from 'redux-saga'
const initialState = {
numberA: 10,
numberB: 20,
};
const incrementReducer = (state = initialState, action) => {
switch (action.type) {
case "TriggerA": {
state.numberA += 1;
return { ...state };
break;
}
case "TriggerB": {
state.numberB += 1;
return { ...state };
break;
}
default:
return state;
}
};
const sagaMiddleware = createSagaMiddleware()
const store = createStore(incrementReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(watchIncrementAsync)
function* incrementAsyncA() {
yield delay(2000)
yield put({ type: 'TriggerA' })
}
//模拟请求
const ajax = () => new Promise(resolve=>setTimeout(()=>{
console.log('返回数据')
resolve()
}, 3000))
function* incrementAsyncB() {
yield call(ajax)
yield put({ type: 'TriggerB' })
}
function* watchIncrementAsync() {
yield takeEvery('Trigger_Async_A', incrementAsyncA)
yield takeEvery('Trigger_Async_B', incrementAsyncB)
}
class Box extends Component {
constructor(props) {
super(props);
}
onClick_A() {
this.props.dispatch({ type: "TriggerA" });
}
onClick_B() {
this.props.dispatch({ type: "TriggerB" });
}
onClick_Async_A() {
this.props.dispatch({ type: "Trigger_Async_A" });
}
onClick_Async_B() {
this.props.dispatch({ type: "Trigger_Async_B" });
}
render() {
return (
<View>
<View>
<Button title={'click_A'} onPress={()=>{
this.onClick_A();
}}/>
<Button title={'异步click_A'} onPress={()=>{
this.onClick_Async_A();
}}/>
<Text>{this.props.number_A}</Text>
</View>
<View>
<Button title={'click_B'} onPress={()=>{
this.onClick_B();
}}/>
<Button title={'异步click_B'} onPress={()=>{
this.onClick_Async_B();
}}/>
<Text>{this.props.number_B}</Text>
</View>
</View>
);
}
}
const B = connect(state => ({
number_A: state.numberA,
number_B: state.numberB
}))(Box);
class App extends Component {
render() {
return (
<Provider store={store}>
<B />
</Provider>
);
}
}
export default App;
redux-saga简易使用
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Redux-Thunk其store下的actions只是普通的actionCreator,真正异步操作放在API里...
- Redux 的核心理念是严格的单向数据流,只能通过 dispatch(action) 的方式修改 store,流程...
- 本文转自我的博客阅读原文。 整体感知 使用redux-saga封装异步操作 将watchFetchData这个Sa...
- 上一篇文章介绍了redux-thunk中间件,redux-thunk中间件主要使action返回函数成为了可能,可...