首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Redux / Redux Saga -如何等待商店更新?

Redux / Redux Saga -如何等待商店更新?
EN

Stack Overflow用户
提问于 2018-01-09 19:34:00
回答 1查看 4K关注 0票数 5

我正在使用React和Redux和Sagas来创建一个纸牌游戏模拟器。我需要创建一个函数来更新redux状态,等待新的状态并再次运行。我不确定这样的事情在React Redux中是不是可能的。下面是我试图实现的目标的简化版本:

代码语言:javascript
运行
复制
function endTurn() {
  // do something
}

function playerTurn(playerHand) {
  const decision = getPlayerDecision(playerHand);
  updatePlayerHand(decision); // this dispatches an action to update redux state

  // If player chose to 'Stand', the game ends.
  // Otherwise, it's player's turn again.
  if(decision === 'Stand') {
    endTurn();
  } else {
    // here I need the updated hand, how do I get it?
    playerTurn(updatedHand);
  }
}

一个显而易见的解决方案是将这个逻辑放在'componentWillReceiveProps‘中,但它看起来并不正确,我相信它最终会出现很多but。直觉上,这感觉像是Redux Saga的工作,但我在文档中找不到任何相关的东西。有什么建议吗?

解决方案:Krasimir使用yield select的答案为我指明了正确的方向。下面是我结束的代码的简化版本:

代码语言:javascript
运行
复制
import { put, takeEvery, select } from 'redux-saga/effects';

function* playPlayerTurn() {

  const playerHand = yield select(getPlayerHand);
  const decision = getPlayerDecision(playerHand);

  // some action that executes the decision
  // the action results in a change to playerHand
  yield put({
    type: `PLAY_PLAYER_DECISION`,
    decision,
  });

  // If player chose to 'Stand', the turn ends.
  // Otherwise, it's player's turn again.
  if(decision === 'Stand') {
    console.log('PLAYER OVER');
  } else {
    console.log('PLAYER AGAIN');
    yield put({
      type: `PLAY_PLAYER_TURN`,
    });
  }
}

export function* playerTurnWatcher() {
  yield takeEvery(`PLAY_PLAYER_TURN`, playPlayerTurn);
}

本质上,我可以递归地调用这个传奇

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-09 20:03:58

让我们假设您发送一个有效负载为decision的操作PLAYER_HAND

代码语言:javascript
运行
复制
import { select, takeLatest } from 'redux-saga/effects';

const waitForPlayerTurn = function * () {
  takeLatest(PLAYER_HAND, function * (decision) {
    // at this point the store contains the right `decision`
    if(decision === 'Stand') {
      endTurn();
    } else {
      playerTurn(yield select(getUpdateHand)); // <-- getUpdateHand is a selector
    }
  });
}

当然,您还必须运行waitForPlayerTurn传奇。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48167304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档