How de we get hold of the redux state, and how do we dispatch an action from within a react component ?
In the cakeContainer we want to display the number of cakes(which is part of the redux state), and also dispatch the BUY_CAKE
action on a button click.
mapStateToProps
When you want to access the redux state in the component, you define mapStateToProps
function. It gets the redux state as a parameter which can be used to retrieve the appropriate state properties.
mapDispatchToProps
Similary for dispatching actionsm we have mapDispatchToProps
function. This function gets the redux dispatch method as a parameter and allow us to map action creators to props in our application.
mapDispatchToProps를 사용해야만 컴포넌트의 props로부터 dipatch를 사용할 수 있는 것은 아님에 주의한다.
🔗 https://react-redux.js.org/using-react-redux/connect-mapdispatch
connect
All this is possible because of the connect
function from react-redux. The connect function connects a react component to the redux store.
import React from 'react';
import { connect } from 'react-redux';
import { buyCake } from '../redux';
function CakeContainer(props) {
return (
<div>
<h2>Number of cakes - {props.numOfCakes}</h2>
<button onClick={props.buyCake}>Buy Cake</button>
</div>
)
}
// (1) define a new function called mapStateToProps
const mapStateToProps = state => {
return {
numOfCakes: state.numOfCakes
}
};
// (2) define a new function called mapDispatchToProps
const mapDispatchToProps = dispatch => {
return {
/* create a property called by buyCake,
equals to an arrow function which dispatches the action creator from redux. */
buyCake: () => dispatch(buyCake())
}
}
// (3) connect these two functions with our react component
export default connect(mapStateToProps, mapDispatchToProps)(CakeContainer)
이제 브라우저의 Number of cakes 에 현재 개수가 뜨고 Buy Cake 버튼을 누르면 개수가 하나씩 줄어든다.