Commit
Flow
Add PttPostContent.js
import React, {Component} from "react";
import {connect} from 'react-redux'
const PttPostContent = ({pttPost}) => {
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}
}
export default connect(mapStateToProps)(PttPostContent)
Add PttPostContent component to App.js
import React from 'react';
import PttPosts from "./components/PttPosts";
import PttPostContent from "./components/PttPostContent"
function App() {
return (
<div>
<div>
<PttPosts />
</div>
<div>
<PttPostContent />
</div>
</div>
);
}
export default App;
When button in PttPosts list was clicked, selectPttPost will be called
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)
Based on the function, selectPttPost will be called
src/actions/index.js
export const selectPttPost = pttPost => {
return {
type: "PTT_POST_SELECTED", //required attribute
payload: pttPost
};
};
mapStateToProps in PttPostContent will be called as well
沒有留言:
張貼留言