我正在使用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);
}
基本上,我能够递归地调用传奇
答案 0 :(得分:1)
假设您发送的行为PLAYER_HAND
的有效负载为decision
。
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
传奇。