使用put in callback

时间:2017-04-25 14:23:58

标签: react-native redux-saga

我正在使用react-native和saga,我希望在请求成功时发出警报。我想知道如何在警报回调中添加操作,以及是否有更好的方法来执行此操作。

function* userRequest(action) {
    try {
        const user = yield call(Api.post, Routes.REQUEST_USER, params);
        yield put({type: types.REQUEST_OK, user: user});
    } catch(e) {
        yield put({type: types.REQUEST_FAILED, user: user});
    }
}

function* requestOk(action) {
    Alert.alert(
        'User',
        'User request ok!',
        [
            //I know this is wrong
            {text: 'OK', onPress: () => yield put({type: types.NAVIGATION_BACK})},
        ],
        { cancelable: false }
    )
}

function* userSaga() {
    yield takeEvery(types.USER_REQUEST, userRequest);
    yield takeEvery(types.REQUEST_OK, requestOk);
}

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以在承诺中编写Alert.alert()方法,并根据用户选择的选项解决或拒绝。

在Promise中创建警报

function showAlert(){
  return new Promise((resolve, reject) => {
    Alert.alert(
      'User',
      'User request ok!',
      [
        {text: 'OK', onPress: () => resolve('confirmed') },
        {text: 'Cancel', onPress: () => reject('canceled')}
      ],
      { cancelable: false }
    )
  })
}

在你的发电机......

function* requestOK(){
   try{
     const confirm = yield call(showAlert);

     //promise resolved, user confirmed
     yield put({type: types.NAVIGATION_BACK});

   }catch(error){
      //user selected cancel
   }
}

https://github.com/redux-saga/redux-saga/issues/508#issuecomment-243336353

答案 1 :(得分:0)

takeEvery采用可选参数,因此我发现执行此操作的最佳方法是将商店传递给传奇,然后使用store.dispatch触发您的操作:

import {createStore} from 'redux';
const store = createStore(...)  // you'll already have this somewhere

---

function* userSaga(store) {
  yield takeEvery(types.REQUEST_OK, requestOk, store);

---

function* requestOk(store, action) {  // store is now the first arg
  Alert.alert(
    'User',
    'User request ok!',
    [
        {text: 'OK', onPress: () => store.dispatch({type: types.NAVIGATION_BACK})},
    ],
    { cancelable: false }
  )
}

答案 2 :(得分:0)

您可以使用eventChannel

const ob = {
    One: 1,
    Two: 2,
    Three: 3,
    Four: 4
};

for (const key of Object.keys(ob)) {
    if (ob[key] <= 3)
        delete ob[key];
}