【前言】
又是一個禮拜的煎熬......但還是得要繼續看redux,加油加油
【正文】
昨天把presentational component
順勢寫完了,今天就來寫container component
吧!在開始撰寫之前,所謂的container component其實就是一個使用store.subscribe()
讀取store
中一部分的state當成props傳給presentational component render的component,所以原則上,我們並不會在container component中撰寫任何有關html標籤所構成的架構碼。
而在這些container component
裡面是這樣的:
mapStateToProps()
mapDispatchToProps()
connect()
把mapStateToProps()和mapDispatchToProps()來產生該container component
所以我們可以知道container component是透過React Redux library 的 connect()產生來的。
// import react-redux connect()
import { connect } from 'react-redux';
// import action creator
import { toggleTodo } from '../actions';
// import TodoList.js(presentational component)
import TodoList from '../components/TodoList';
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
return todos;
case 'SHOW_COMPLETED':
return todos.filter(t => t.completed);
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed);
default:
return todos;
}
};
// mapStateToProps()可以將store中state當成props傳入component
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter),
};
};
// mapDispatchToProps()可以注入dispatch到component
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id));
}
};
};
// 利用connect()產生container component
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps,
)(TodoList);
export default VisibleTodoList;
import { connect } from 'react-redux';
import { setVisibilityFilter } from '../actions';
import Link from '../components/Link';
const mapStateToProps = (state, ownProps) => {
return {
active: ownProps.filter === state.visibilityFilter,
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
dispatch(setVisibilityFilter(ownProps.filter));
},
};
};
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps,
)(Link);
export default FilterLink;