我正在使用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‘中,但它看起来并不正确,我相信它最终会出现很多but。直觉上,这感觉像是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);
}本质上,我可以递归地调用这个传奇
发布于 2018-01-09 20:03:58
让我们假设您发送一个有效负载为decision的操作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传奇。
https://stackoverflow.com/questions/48167304
复制相似问题