从 API 调用获取的 Slug 数据在 ReactJS 窗口中未显示。

huangapple go评论59阅读模式
英文:

Slug Data from Api call not displaying in window with reactjs

问题

以下是您要翻译的内容:

"I'm pretty sure I did everything right in this code below but I have no idea why the data in the clientside won't display. When I try to console the result in the UseEffect hook but and I get all data but using them in the html just doesn't work.

What worries me more is that this code worked fine for a short time before it totally stopped displaying these details in the html"

请注意,代码部分已经排除在外,这是内容的翻译部分。

英文:

I'm pretty sure I did everything right in this code below but I have no idea why the data in the clientside won't display. When I try to console the result in the UseEffect hook but and I get all data but using them in the html just doesn't work.

What worries me more is that this code worked fine for a short time before it totally stopped displaying these details in the html

import React, {
  useContext,
  useEffect,
  useReducer,
  useRef,
  useState,
} from 'react';
import { Link, useParams } from 'react-router-dom';
import axios from 'axios';
import { API_URL, getError } from '../utils';
import { Store } from '../Store';
import { toast } from 'react-toastify';
import moment from 'moment';
import MessageBox from './MessageBox';
import { Button } from 'react-bootstrap';
import LoadingBox from './LoadingBox';

const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_REQUEST':
      return { ...state, loading: true };
    case 'FETCH_SUCCESS':
      return { ...state, blog: action.payload, loading: false };
    case 'FETCH_FAIL':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};

export default function BlogpostScreen() {
  let reviewsRef = useRef();

  const [comment, setComment] = useState('');

  const params = useParams();
  const { slug } = params;

  const [{ loading, error, blog }, dispatch] = useReducer(
    reducer,
    {
      blog: {},
      loading: true,
      error: '',
    }
  );

  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_REQUEST' });
      try {
        const result = await axios.get(`${API_URL}/api/blogs/slug/${slug}`);
        dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
      } catch (err) {
        dispatch({ type: 'FETCH_FAIL', payload: getError(err.message) });
      }
    };
    fetchData();
  }, [slug]);

  const { state } = useContext(Store);
  const { userInfo } = state;

  return (
    <div className="position-relative mb-3">
      <img
        className="img-fluid w-100"
        src={blog.image}
        alt={blog.name}
        style={{ objectFit: 'cover' }}
      />
      <div className="bg-white border border-top-0 p-4">
        <div className="mb-3">
          <Link
            className="badge badge-primary text-uppercase font-weight-semi-bold p-2 mr-2"
            to={{
              pathname: '/search',
              search: `category=${blog.category}`,
            }}
          >
            {blog.category}
          </Link>
          <a className="text-body" href="/">
            {moment(blog.createdAt).format('MMMM Do YYYY, h:mm:ss a')}
          </a>
        </div>
        <h1 className="mb-3 text-secondary text-uppercase font-weight-bold">
          {blog.name}
        </h1>
        <div dangerouslySetInnerHTML={{ __html: blog.post }}></div>
      </div>
      <div className="d-flex justify-content-between bg-white border border-top-0 p-4">
        <div className="d-flex align-items-center">
          <img
            className="rounded-circle mr-2"
            src="img/user.jpg"
            width="25"
            height="25"
            alt=""
          />
          <span>KimmoTech</span>
        </div>
        <div className="d-flex align-items-center">
          <span className="ml-3">
            <i className="far fa-eye mr-2"></i>
            {blog.views}
          </span>
          <span className="ml-3">
            <i className="far fa-comment mr-2"></i>
            {blog.numReviews}
          </span>
        </div>
      </div>
    </div>
  );
}

In the backend, I had this:

blogRouter.get('/slug/:slug', async (req, res) => {
  const blog = await Blog.findOneAndUpdate(
    { slug: req.params.slug },
    { $inc: { views: 1 } },
    { new: true }
  );
  if (blog) {
    res.send({blog});
  } else {
    res.status(404).sendStatus({ message: 'Blogpost Not Found' });
  }
});

答案1

得分: 0

我意识到问题是因为我向前端发送了这样的对象res.send({blog});。所以我将

原来的代码修改为:

blogRouter.get('/slug/:slug', async (req, res) => {
  const blog = await Blog.findOneAndUpdate(
    { slug: req.params.slug },
    { $inc: { views: 1 } },
    { new: true }
  );
  if (blog) {
    res.send(blog);
  } else {
    res.status(404).sendStatus({ message: 'Blogpost Not Found' });
  }
});
英文:

I realized the issue was because I was sending an object like this res.send({blog}); to the frontend. So I changed

this:

blogRouter.get('/slug/:slug', async (req, res) => {
  const blog = await Blog.findOneAndUpdate(
    { slug: req.params.slug },
    { $inc: { views: 1 } },
    { new: true }
  );
  if (blog) {
    res.send({blog});
  } else {
    res.status(404).sendStatus({ message: 'Blogpost Not Found' });
  }
});

to this:

blogRouter.get('/slug/:slug', async (req, res) => {
  const blog = await Blog.findOneAndUpdate(
    { slug: req.params.slug },
    { $inc: { views: 1 } },
    { new: true }
  );
  if (blog) {
    res.send(blog);
  } else {
    res.status(404).sendStatus({ message: 'Blogpost Not Found' });
  }
});

huangapple
  • 本文由 发表于 2023年4月6日 22:44:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定