react-无状态组件

import React, { Component } from "react";
//import PostItem from "./PostItem";

/**将无状态组件 嵌入 */

function PostItem(props) {
const handleClick = () => {
props.onVote(props.post.id);
};
const { post } = props;
return (
<li>
<div>{post.title}</div>
<div>
创建人:<span>{post.author}</span>
</div>
<div>
创建时间:<span>{post.date}</span>
</div>
<div>
<button onClick={handleClick}>点赞</button>
&nbsp;
<span>{post.vote}</span>
</div>
</li>
);
}

//export default PostItem

class PostList extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
this.timer = null;
this.handleVote = this.handleVote.bind(this); //ES6 class 中 必须手动绑定this
}

//render 后
componentDidMount() {
// 用setTimeout模拟异步从服务器端获取数据
this.timer = setTimeout(() => {
this.setState({
posts: [
{
id: 1,
title: "大家一起来讨论React吧",
author: "张三",
date: "2017-09-01 10:00",
vote: 0
},
{
id: 2,
title: "前端框架,你最爱哪一个",
author: "李四",
date: "2017-09-01 12:00",
vote: 0
},
{
id: 3,
title: "Web App的时代已经到来",
author: "王五",
date: "2017-09-01 14:00",
vote: 0
}
]
});
}, 1000);
}

componentWillUnmount() {
if (this.timer) {
clearTimeout(this.timer);
}
}

handleVote(id) {
//根据帖子id进行过滤,找到待修改vote属性的帖子,返回新的posts对象
const posts = this.state.posts.map(item => {
const newItem = item.id === id ? { ...item, vote: ++item.vote } : item;
return newItem;
});
this.setState({
posts
});
}

render() {
return (
<div>
帖子列表
<ul>
{this.state.posts.map(item => (
<PostItem post={item} onVote={this.handleVote} />
))}
</ul>
</div>
);
}
}
export default PostList;

猜你喜欢

转载自www.cnblogs.com/iOS-mt/p/10296440.html