// src/index.js
...
import { createStore } from 'redux';
import rootReducer from './modules';
const store = createStore(rootReducer);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
...
import { Provider } from 'react-redux';
...
root.render(
<Provider store={store}>
<App />
</Provider>
);
yarn add redux-devtools-extension
// src/index.js
...
import { devToolsEnhancer } from 'redux-devtools-extension'
const store = createStore(rootReducer, devToolsEnhancer());
...
다시 앱 실행하면 개발자도구 Redux 탭에서 확인 가능
connect( mapStateToProps, mapDispatchToProps )
- mapStateToProps는 리덕스 스토어 안 상태를,
- mapDispatchToProps는 액션 생성 함수를
- 컴포넌트의 props로 넘겨주기 위해 설정하고 사용하는 함수
const makeContainer = connect( mapStateToProps, mapDispatchToProps )
makeContainer(타깃 컴포넌트)
// containers/CounterContainer.js
import Counter from '../components/Counter';
import {connect} from 'react-redux'
// 액션 생성함수 import
import { increase, decrease } from '../modules/counter';
const CounterContainer = ({number, increase, decrease}) => {
return (
<Counter number={number} onIncrease={increase} onDecrease={decrease}/>
)
};
const mapStateToProps = state => ({
number : state.counter.number,
})
const mapDispatchToProps = dispatch => ({
increase : () => {
dispatch(incresae());
},
decrease : () => {
dispatch(decresae());
}
})
export default connect(mapStateToProps, mapDispatchToProps)(CounterContainer);
// src/App.js
...
return (
<div>
<CounterContainer/>
<hr>
<Todos/>
</div>
)
// container/CounterContainer.js
import {bindActionCreators} from 'redux';
...
export default connect(
state => ({
number : state.counter.number,
}),
dispatch => bindActionCreators(
{
increase,
decrease
},
dispatch,
)
)(CounterContainer)
// container/CounterContainer.js
...
export default connect(
state => ({
number : state.counter.number,
}),
{
increase,
decrease
},
)(CounterContainer)
import { connect } from "react-redux";
import { changeInput, insert, toggle, remove } from "../modules/todos";
import Todos from "../components/Todos";
const TodosContainer = ({input, todos, changeInput, insert, toggle, remove}) => {
return (
<Todos
input = {input}
todos = {todos}
onChangeInput = {changeInput}
onInsert = {insert}
onToggle = {toggle}
onRemove = {remove}
/>
)
}
export default connect(
// 비구조화 할당을 통해 todos를 분리하여
// state.todos.input 대신 todos.input을 사용
({todos}) => ({
input : todos.input,
todos : todos.todos,
}),
{
changeInput,
insert,
toggle,
remove,
},
)(TodosContainer)
// src/App.js에서 <TodosContainer/>로 변경해주고
// components/Todos.js 컴포넌트도 받아온 props를 사용하도록 구현
뛰어난 글이네요, 감사합니다.