上一篇中我們已經將大部分的內容與功能都建立完成,最後要建立的便是給使用者選擇要看到那些Todo的選項按鈕,顯示篩選分別為 :
流程圖 :
import { connect } from "react-redux";
import { setVisibilityFilter } from "../Store/Action/Action";
import Link from "../Presentational Component/Link";
//當State更新後自動調用
const mapStateToProps = (state, ownProps) => {
//ownProps : 傳遞給FilterLink組件的元素,包含props與childran(標籤中的元素)
return {
active: ownProps.filter === state.visibilityFilter
}
}
//將onClick傳遞給Presentational Components作為callback
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
console.log(ownProps.filter)
dispatch(setVisibilityFilter(ownProps.filter))
}
}
}
//將判斷filter的結果與callback藉由connect傳遞給Link
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
)(Link)
export default FilterLink
import React from "react";
const Link = (props) => {
if(props.active){
return(
<span>{props.children}</span>
)
}
return(
<a
href="#"
onClick={e=>{
e.preventDefault();
props.onClick()
}}
>
{props.children}
</a>
)
};
export default Link;
import React from "react";
import FilterLink from "../Container Component/FilterLink";
const Footer = (props) => (
<p>
Show:
{" "}
<FilterLink filter="SHOW_ALL">
{/* childran */}
All
</FilterLink>
{", "}
<FilterLink filter="SHOW_ACTIVE">
Active
</FilterLink>
{", "}
<FilterLink filter="SHOW_COMPLETED">
Completed
</FilterLink>
</p>
)
export default Footer
節由這個練習可以更加瞭解Redux處理數據的方法,將數據交給Redux進行處理後再將處理完的數據傳遞給Presentational Component進行UI渲染,不需要再考慮組件之間state的傳遞、提升state的問題,在更大型的專案中更能夠體現使用Redux的好處。
參考資料 :
從Redux 的作者學習它