JavaScript .includes()仅在页面刷新后才能工作

时间:2020-08-23 17:43:34

标签: javascript reactjs

我正在使用.includes来检查db中的Likes数组是否已经包含此用户的ID,该ID可以正常工作,但是它仅在刷新页面或导航到其他页面然后返回之后才起作用。 我看过各种类似的问题,但似乎找不到答案/解决方案。 为什么不刷新页面就无法正常工作?

注意:当我检查用户ID是否等于帖子的作者ID或经过身份验证的用户是否已经喜欢它post.author && post.author.id === _id || post.likes && post.likes.includes(_id)时,第一条语句可以正常工作而无需刷新页面。第二个似乎有问题。

Post.js


    const Post = (props) => {
      const [post, setPost] = useState({});
      const [error, setError] = useState(false);
      const id = props.match.params.id;
    
    
      const loadSinglePost = (id) => {
        read(id).then((data) => {
          if (error) {
            console.log(data.error);
            setError(data.error);
          } else {
            setPost(data);
            console.log(data);
          }
        });
      };
    
      useEffect(() => {
        loadSinglePost(id);
      }, [props]);
    
    const likePost = (id) => {
        const {
          user: { _id },
          token,
        } = isAuthenticated();
        fetch(`${API}/like/${_id}/${id}`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            id: id,
          }),
        })
          .then((result) => {
            const {user: {_id}} = isAuthenticated()
            let updatedPost = { ...post };
{/* condition only works after page refresh. Before page refresh, likes 
are continuously being pushed to array even when the condition has been met. */}
          if (post.likes && post.likes.includes(_id)){
           return null
          } else {
            updatedPost.likes.push(id);
            setPost(updatedPost);
          }})
          .catch((err) => {
            console.log(err);
          });
      };
    
     const {user: {_id}} = isAuthenticated()
      return (
         <div>
{/* condition only works after page refresh. Before page refresh, button is  always displayed even when the condition has been met. */}
           {post.likes && post.likes.includes(_id) ? "" :
             <button>Like </button>}
         </div>)
        }

controllers / posts.js

   exports.like = (req, res) => {
         
   Post.findByIdAndUpdate(req.params.id, {
   $push: {likes: req.profile._id}
   }, {new: true}).exec((err, result) => {
    if (err) {
    return res.status(422).json({error: err})
     } else {
      return res.json(result)
       }
      })
     }

0 个答案:

没有答案