如何在 React Native 中使用 yield inside map

How to use yield inside map for React Native

我的目标是在 map.

中执行分叉函数

这是我试过的方法:

  function* doSomethingWithItem(item) {}

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

也尝试使用 yield fork() 但出现错误 "yield is a reserved word..."

doSomethingWithItem() 未被调用。

感谢帮助。

由于 map 使用 lambda 函数,您实际上不能直接从那里产生一些东西。

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

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 停止的错误。