使用逗号运算符在 redux 工具包中的同一调度中调用多个化简器不起作用



根据MDN:

The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand.
This lets you create a compound expression in which multiple expressions are evaluated,
with the compound expression's final value being the value of the rightmost of its member expressions.
This is commonly used to provide multiple parameters to a for loop

所以我认为这样的东西会起作用:

const gameData = useDispatch();
gameData((
readGameAnswers(props.gameAnswers),
readGameAnswersImage(props.gameAnswersImages as string[]),
readCorrectAnswer(props.correctAnswer)));

(其中3个读取功能是在商店中定义的缩减器(

不过,这种行为并不是我所期望的——只调用了最后一次读取。为什么会发生这种情况?它不应该按照逗号运算符的定义工作吗?

不幸的是,不,这不起作用,因为每个方法调用只提供一个操作,并且由于逗号的行为,只有最后一个返回给调度器(gameData(。您正在寻找的是一个将多个reducer调用组合为一个的动作创建者。

我相信这个问题已经找到了你想要的答案!

最新更新