如何在React Native的地图内部使用yield

时间:2019-01-15 06:04:25

标签: react-native redux-saga

我的目标是在map内部执行派生函数。

这是我尝试过的:

  function* doSomethingWithItem(item) {}

  yield all(items.map(item => {
    // ... some item checking
    return fork(doSomethingWithItem, item);
  }));

也尝试使用yield fork(),但收到错误消息“ yield是保留字...”

doSomethingWithItem()没有被调用。

感谢帮助。

1 个答案:

答案 0 :(得分:0)

由于map使用lambda函数,因此您实际上无法直接从那里产生任何东西。

yield all是正确的方法,但是在这种情况下,fork效果比call更合适,因为它被阻塞了,因此保留了项目处理顺序(如果这很重要):

function * doSomethingWithItem ( item ) {
  console.log('doSomethingWithItem', item)
}

function * doSomethingWithAllItems ( items ) {
  console.log('doSomethingWithAllItems')
  yield all(items.map(item =>
    call(doSomethingWithItem, item),
  ))
  console.log('done doSomethingWithAllItems')
}

function * mySaga () {
  yield call(doSomethingWithAllItems, [1, 2, 3, 4, 5])
}

我还检查了您的代码,doSomethingWithItem确实可以在我的环境中工作。尝试将代码包装在try / catch中,也许您遇到使saga停止的错误。