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

标签 reactjs redux react-redux redux-saga

我正在使用 React 与 Redux 和 Sagas 来创建一个纸牌游戏模拟器。我需要创建一个函数来更新 redux 状态,等待新状态并再次运行。我不确定在 React Redux 领域是否/如何可能发生类似的事情。以下是我想要实现的目标的简化版本:

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”中,但它看起来并不正确,而且我确信它最终会出现很多错误。直观上,这感觉像是 Redux Saga 的工作,但我在文档中找不到任何相关内容。有什么建议吗?

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

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);
}

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

最佳答案

假设您分派(dispatch)一个操作 PLAYER_HAND,其中负载是决策

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 saga。

关于reactjs - Redux/Redux Saga - 如何等待商店更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48167304/

相关文章:

react-native - 当 native 应用程序启动时,将初始状态从 API 调用传递到 createStore

reactjs - 如何将 Redux 的 useSelector 和 useDispatch Hook 与 PropTypes 结合使用

javascript - React - 如何管理多个动态创建的受控输入的状态?

javascript - 上下文API : How would one share data between contexts in React?

javascript - 是否可以从vanilla javascript导入和使用react-redux组件

reactjs - 受控组件的内存使用问题

javascript - 如何处理 reducer 中的异步 promise

javascript - 如何更新react-redux中的状态?

javascript - 如何使用 React.useRef 获取实际的 Dom 节点? Element.getBoundingClientRect() 不适用于 useRef 变量

javascript - 在 Redux 中获取数据