为数组中的类似react child对象创建单独的状态

时间:2018-09-11 20:56:45

标签: reactjs

我创建了一个小型社交媒体应用,其中有一个喜欢按钮来喜欢该帖子。当我按第一个按钮上的like时,第二个帖子的like也会改变颜色,这是基于状态的。

代码如下:

Likes.js

<LikedPanel
    posts_id={posts_id}
    person_id={person_id}
    toggleLikePost={this.toggleLikePost}
    liked={this.state.liked}
/>

const LikedPanel = ({posts_id, person_id, liked, toggleLikePost}) => (
<Panel onClick={() => toggleLikePost(posts_id, person_id)}>
    {liked
        ?
        <Fragment>
            <LikeIcon nativeColor={indigo[500]}/>
            <LikedText>Like</LikedText>
        </Fragment>
        :
        <Fragment>
            <LikeIcon/>
            <LikeText>Like</LikeText>
        </Fragment>
    }
</Panel>
);

toggleLikePost = (posts_id, person_id) => {
    // make api call and then setState
    this.setState(liked: res.data.liked);
};

  

更新

Posts.js

const Posts = ({ feed, deletePost }) => (
<Card style={{ margin: '25px 0'}} square>
    <ContentMedia post={feed.post} deletePost={deletePost} />
    <Like liked={feed.post.likes.length > 0} posts_id={feed.post.id} person_id={feed.post.person_id} />
    <Comments post_id={feed.post.id} comments={feed.post.comments} />
</Card>
);

Newsfeed.js

<div style={{ maxWidth: '500px', margin: '0 auto', paddingTop: '20px'}}>            
{this.renderPosts(this.state.feed)}
</div>


renderPosts = (feeds) =>
    feeds.map(feed => <Posts key={feed.post.id} feed={feed} deletePost={this.deletePost} />);

刷新后加载正常。但是,当我单击任意一个帖子时,其他所有的图标都被切换,反之亦然。我看到它对所有元素使用相同的状态。有没有办法告诉反应每个帖子的面板都有自己的独立状态?

1 个答案:

答案 0 :(得分:0)

可以存储一组喜欢的帖子,而不是存储所有类似按钮用来确定是否应切换的布尔值liked。然后,您可以将喜欢的帖子ID添加到该数组,并在LikedPanel中检测当前的帖子ID是否在liked数组中。

<LikedPanel
    posts_id={posts_id}
    person_id={person_id}
    toggleLikePost={this.toggleLikePost}
    liked={this.state.liked.indexOf(posts_id) !== -1 }
/>

toggleLikePost = (posts_id, person_id) => {
    // make api call and then setState

    this.setState(prevState => {
        // add post id to liked array only if it's not added yet
        if (prevState.liked.indexOf(posts_id) === -1) {
            return {liked: [...prevState.liked, posts_id]};
        } 
    });
};