简体   繁体   English

为什么我的本地 state 被覆盖? 反应

[英]Why is my local state being overridden? React

I'm using useState hook to manage state.我正在使用 useState 挂钩来管理 state。 Whenever a user clicks likePost, setData is called with newData.每当用户点击likePost,setData 就会被newData 调用。 This causes the state to update as seen in the images and the item loses postedBy name item.postedBy.name becomes undefined.这会导致 state 更新,如图像中所示,并且项目丢失了postedBy name item.postedBy.name 变得未定义。 This causes the user-title div to empty and collapse.这会导致用户标题 div 清空并折叠。

before likePost之前喜欢发帖

after likePost点赞后

The relevant code includes:相关代码包括:

const Home = () => {
const [data, setData] = useState([]);
// for access to user who's logged in, use context
const {state, dispatch} = useContext(UserContext);
useEffect(()=>{
    fetch('/allposts', {
        headers:{
            "Authorization":"Bearer " + localStorage.getItem("jwt")
        }
    }).then(res=>res.json())
    .then(result=>{
        console.log(result);
        setData(result.posts);
    });     
}, []);

const likePost = (item, id) => {
    fetch('/like', {
        method: "put", 
        headers: {
            "Content-Type":"application/json",
            "Authorization":"Bearer " + localStorage.getItem("jwt")
        },
        body: JSON.stringify({
            postId:id
        })
    }).then(res=>res.json())
    .then(result=>{
        const newData = data.map(item=>{
            if(item._id == result._id){
                return result;
            }else{
                return item;
            }
        })
        setData(newData);
    }).catch(err=>{
        console.log(err);
    })
};

and

return (
    <div className="home">
        {
            postsReversed.map(item=>{   
                return(
                    <div className="card home-card" key={item._id}>
                        <h5 className="user-title"><Link to={item.postedBy._id !== state._id ? "/profile/"+item.postedBy._id : "/profile/"}>{item.postedBy.name}</Link>{item.postedBy._id == state._id
                            && <i className="material-icons" style={{
                                float: "right"
                        }}
                        onClick={()=>deletePost(item._id)}
                        >delete</i>
                        }</h5>
                        <div className="card-image">
                            <img src={item.photo} />
                        </div>
                        <div className="card-content">
                            <div>
                            {item.likes.includes(state._id)
                                ?
                            <i className="material-icons"
                                onClick={()=>{unlikePost(item._id)}}
                            >thumb_down</i>
                                : 
                            <i className="material-icons"
                                onClick={()=>{likePost(item._id)}}
                            >thumb_up</i>
                            }

This seems to work as intended, you're replacing an item from the data array with the one that you get as a response from the /like endpoint.这似乎按预期工作,您将data数组中的一个项目替换为您从/like端点获得的响应。 You can either change your server to return the same data structure for an item as /allposts or use something like:您可以更改您的服务器以返回与/allposts相同的项目数据结构或使用类似的东西:

....
if (item._id == result._id) {
    return { ...item, likes: result.likes };
}
....

To only update part of the item.仅更新部分项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM