Redux - 更深入理解 mapStateToProps
Commit
我犯的錯誤
我發現 PttPosts 的實作好像不太對。
PttPosts.js
import React, {Component} from "react";
import {connect} from 'react-redux'
import {selectPttPost} from '../actions'
class PttPosts extends Component {
renderPosts() {
return this.props.pttPosts.map((post) => {
return <div key={post.title}>
${post.title} / ${post.author} <button onClick={() => this.props.selectPttPost(post)} key={post.title}>Click</button>
</div>
});
}
render() {
return <div>{this.renderPosts()}</div>
}
}
// incorrect
const mapStateToProps = (state) => {
console.log("mapStateToProps", state)
return state;
}
export default connect(mapStateToProps, { selectPttPost })(PttPosts)
後來我理解到 "mapStateToProps" 可以指定 render function 中使用的屬性名稱。
就像 PttPostContent.js 一樣
import React, {Component} from "react";
import {connect} from 'react-redux'
const PttPostContent = ({pttPost}) => { // 2. 所以在 render 的時候可以透過屬性名稱拿到資料
if (!pttPost) {
return <div />
}
return <div>
<div>${pttPost.title}</div>
<div>${pttPost.author}</div>
</div>
}
const mapStateToProps = (state) => {
console.log("mapStateToProps", state)
return {pttPost: state.selectedPttPost} // 1. 因為 "pttPost" 被放進 props 裡面了
}
export default connect(mapStateToProps)(PttPostContent)