Commit
Mistake I made
I find PttPosts implementation component seems incorrect.
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)
And then I realized “mapStateToProps” can put the attribute name used when render function was called.
Just like PttPostContent.js
import React, {Component} from "react";
import {connect} from 'react-redux'
const PttPostContent = ({pttPost}) => { // 2. So we can get data from attribute when redering
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. Because “pttPost” was put to props
}
export default connect(mapStateToProps)(PttPostContent)
沒有留言:
張貼留言