gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:08:20 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com