Your reducer must be pure. Currently it is not pure. It calls deal()
which calls getRandom()
which relies on Math.random()
and thus is not pure.
This kind of logic (“generating data”, whether randomized or from user input) should be in the action creator. Action creators don’t need to be pure, and can safely use Math.random()
. This action creator would return an action, an object describing the change:
{
type: 'DEAL_CARDS',
cards: ['heart', 'club', 'heart', 'heart']
}
The reducer would just add (or replace?) this data inside the state.
In general, start with an action object. It should describe the change in such a way that running the reducer with the same action object and the same previous state should return the same next state. This is why reducer cannot contain Math.random()
calls—they would break this condition, as they would be random every time. You wouldn't be able to test your reducer.
After you figure out how the action object looks (e.g. like above), you can write the action creator to generate it, and a reducer to transform state and action to the next state. Logic to generate an action resides in action creator, logic to react to it resides in the reducer, reducer must be pure.
Finally, don’t use classes inside the state. They are not serializable as is. You don’t need a Card
class. Just use plain objects and arrays.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…