Redux - 選取文章
把 action creator 引入到 component
把 action creator 傳入 connect
在 render function 裡印出 this.props -> 傳入 connect 之後,actionCreator function 就會被加到 this.props 裡面
在按鈕的 onClick 事件加上 arrow function
在 arrow function 裡呼叫 action creator:this.props.selectSong(song) => 點擊按鈕後 state 就會改變
在 mapStateToProp 裡印出 state,可以發現點擊按鈕時會被呼叫
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>
}
}
const mapStateToProps = (state) => {
console.log(state)
return state;
}
export default connect(mapStateToProps, { selectPttPost })(PttPosts)

打開頁面然後點選標題 A 到標題 D,看一下 console log。
可以看到 state 裡面有文章的資訊
