React: Redux state from mapStateToProps not updating after dispatch is called
Answer a question
When I dispatch an action from inside the component (i.e. a button is clicked), the state that is changed in the action is not immediately updated in the component's props. I am connecting the state and dispatch to the props through Redux's connect function. I did notice that it updates properly within the component's rendering.
Game.jsx
const Game = ({ playerCards, add }) => {
const stand = () => {};
const hit = () => {
add(getNextCard());
console.log(playerCards); // Outputs the old state
};
return (
<div className="container--center">
<div className="container__inner--center">
<div className="game-wrapper">
<div className="game-wrapper__inner">
<Player />
<form className="player-actions">
<button type="button" onClick={stand}>
Stand
</button>
<button type="button" onClick={hit}>
Hit
</button>
</form>
</div>
</div>
</div>
</div>
);
};
export default connect(
(state) => {
return {
playerCards: state.cards.player,
};
},
(dispatch) => {
return {
add: (card) => dispatch(addPlayerCard(card)),
};
}
)(Game);
addPlayerCard action
const addPlayerCard = (card = {}) => {
return {
type: ADD_PLAYER_CARD,
card,
};
};
Answers
First state updates are asynchronous.
Second when you dispatch add(getNextCard()) you want to update some state in the UI to be rendered again, so the new state will be available till the next re-render and it does not make any sens trying getting the new state just after the dispatch call.
So the new playerCards value will be printed in the UI (in the render function).
更多推荐
所有评论(0)