【问题标题】:React, Adding data from json to single post component反应,将数据从 json 添加到单个帖子组件
【发布时间】:2020-06-20 00:43:45
【问题描述】:

我尝试用 React 编写网站,到目前为止一切正常。我完全被卡住了。

我有一个工作正常的帖子列表组件。我的问题是,我不知道如何将数据从 JSON 添加到单个帖子组件。我试图将获取我的 JSON 数据从列表文章组件更改为 app.js,然后将其传递给包含我的列表帖子的组件和单个帖子组件,但随后我的 map() 函数出现错误。


//geting data from JSON and passing it through props down
import React, { useEffect, useState } from "react";
import "./style.css";

import SideBar from "../SideBar";
import MainContent from "../MainContent";
import blogData from "../../assets/data/blog.json";

const MainContainer = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const post = blogData.data;
    setPosts(post);
  }, []);

  return (
    <div className="main-container">
      <MainContent posts={posts} />
      <SideBar posts={posts} />
    </div>
  );
};

export default MainContainer;
//mapping through posts
import React from "react";
import "./style.css";
import Post from "../Post";

const MainContent = ({ posts }) => {
  return (
    <main className="main-content">
      {posts.map(post => {
        return <Post key={post.id} post={post} />;
      })}
    </main>
  );
};

export default MainContent;
//Post from list of posts
const Post = ({ post }) => {
  return (
    <div className="post">
      <Animated
        animationIn="bounceInLeft"
        animationOut="fadeOut"
        isVisible={true}
      >
        <h3 className="postTitle">{post.blogTitle}</h3>
        <div className="imgContainer">
          <img
            alt="travel"
            src={require("../../assets/img/" + post.blogImage)}
          ></img>
        </div>
        <p className="postDescription">{post.blogText}</p>
        <NavLink to={`/post/${post.id}`}>
          <h5 className="postLink">Read more</h5>
        </NavLink>
        <h5 className="posteDate">
          Posted on {post.postedOn} by {post.author}
        </h5>
      </Animated>
    </div>
  );
};

export default Post;



这是我的仓库的链接: https://github.com/Gitarrra92/travel-blog/

【问题讨论】:

  • 你遇到了什么错误?

标签: javascript json reactjs


【解决方案1】:

我认为我的组件中应该有一个具有特定 ID 的单个对象的状态。我只是仍然不知道该怎么做。这是我的 SinglePost 组件


const SinglePost = ({ match }) => {
  const [singlePosts, setSinglePost] = useState({});

  useEffect(() => {
    const singlePost = blogSingleData.data;
    setSinglePost(singlePost);
    console.log(singlePost);
  }, [match]);

  return (
    <>
      <Socials />
    </>
  );
};

export default SinglePost;

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多