如何在单个组件上显示来自Redux存储的评论

问题描述 投票:-1回答:2

我已经创建了一个基本的单页应用程序,在初始页上有一些虚拟数据,并且在单击每个项目时,我将用户定向到该项目的各个详细信息页面。我想实现已成功完成的注释和删除注释功能,但是现在当我注释或删除注释时,它不仅会在该单独页面上发生,而且也会在其他所有页面上发生。请参阅沙盒示例,以更好地说明。

https://codesandbox.io/s/objective-feistel-g62g0?file=/src/components/ProductDetails.js

因此,一旦您在单个页面中添加了一些评论,请返回并单击到其他产品,显然,您会看到在其他页面中所做的评论也可以在其中找到。您认为造成此问题的原因是什么?

reactjs redux
2个回答
0
投票

同一状态将被所有不同页面重用。

尝试为每个页面/路由器动态加载不同的负载减少器以使用不同的状态值。

您可以从这里开始

Redux modules and code splitting


0
投票

我找到了自己的逻辑解决方案。您可能会找到更好的解决方案,但这也很好。我想到了使用从URL获得的参数在对象中传递另一个属性,然后按其URL参数过滤注释。这样我就可以根据url参数进行过滤,并仅显示在该特定页面上发表的评论。

因此ProductDetails.js页面应如下所示:

import React, { useState, useEffect } from 'react';
import { Input, Button } from 'semantic-ui-react'
import { connect } from 'react-redux';

const ProductDetails = (props) => {


    const [commentObject, setCommentObject] = useState({
        text: "",
        date: "",
        id: ""
    });

    const clickHandler = () => {
        if (!commentObject.text.trim()) {
            return
        }
        props.addNewComment(commentObject)
        setCommentObject({
            ...commentObject,
            text: ""
        })
        console.log(commentObject.id);
    }
    useEffect(() => {

    }, []);

    return (
        <div>
            {props.posts ? props.posts.text : null}

            {props.comments.filter(comment => {
                return comment.postId === props.match.params.slug
            }).map(({ text, id }) => {

                return (<div key={id}>
                    <p>{text}</p>
                    <Button onClick={() => props.deleteComment(id)} >Delete comment</Button></div>)
            })}
            <Input value={commentObject.text}
                onChange={comment => setCommentObject({ text: comment.target.value, date: new Date(), id: Date.now(), postId: props.match.params.slug })}
            />
            <Button onClick={clickHandler} >Add comment</Button>

        </div>
    );
}
const mapStateToProps = (state, ownProps) => {

    let slug = ownProps.match.params.slug;


    return {
        ...state,
        posts: state.posts.find(post => post.slug === slug),

    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        addNewComment: (object) => { dispatch({ type: "ADD_COMMENT", payload: { comment: { text: object.text, date: object.date, id: object.id, postId: object.postId } } }) },
        deleteComment: (id) => { dispatch({ type: "DELETE_COMMENT", id: id }) }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductDetails);


© www.soinside.com 2019 - 2024. All rights reserved.