You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何跨组件文件传递useState存储的数据?

解决React路由跳转时传递文章ID的问题

1. 调整首页跳转逻辑,将文章ID嵌入URL

你当前的跳转未携带ID,需要把文章ID作为路由参数拼入跳转路径:

export default function HomeCard() { 
  const [latestPosts, setLatestPosts] = useState([]); 
  useEffect(() => { 
      fetch('http://localhost:8000/posts') 
          .then ((res) => res.json()) 
          .then ((data) => setLatestPosts(data.reverse())); 
  }, []); 
  const navigate = useNavigate(); 
  // 修改跳转逻辑,把ID传入路由
  const storePostId = (singlePostId) => { 
    navigate(`/single-post/${singlePostId}`);
  };

  // 遍历文章数组渲染卡片
  return (
    <div>
      {latestPosts.map(post => (
        <Card key={post.id}>
          <CardActionArea onClick={() => storePostId(post.id)}>
            {/* 卡片内容:标题、摘要等 */}
          </CardActionArea>
        </Card>
      ))}
    </div>
  );
}

2. 配置支持动态参数的路由

在路由配置文件(如App.js)中,为SinglePost页面添加带动态参数的路由规则:

import { Routes, Route } from 'react-router-dom';
import HomeCard from './HomeCard';
import SinglePost from './SinglePost';

function App() {
  return (
    <Routes>
      <Route path="/" element={<HomeCard />} />
      {/* 用:postId定义动态参数 */}
      <Route path="/single-post/:postId" element={<SinglePost />} />
    </Routes>
  );
}

3. 在SinglePost组件中获取参数并请求文章数据

使用useParams钩子提取URL中的文章ID,再请求对应数据并保存:

import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';

const SinglePost = () => { 
  const [post, setPost] = useState(null);
  const { postId } = useParams(); // 获取URL中的postId参数

  useEffect(() => { 
    if (postId) {
      fetch(`http://localhost:8000/posts/${postId}`) 
          .then ((res) => res.json()) 
          .then ((data) => setPost(data));
    }
  }, [postId]); // 依赖postId,参数变化时重新请求

  if (!post) return <div>加载中...</div>;

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
      {/* 其他文章内容 */}
    </div>
  );
};

export default SinglePost;

这种方式无需Context API,通过路由参数传递数据是该场景下最直接的解决方案。

内容的提问来源于stack exchange,提问作者postmetric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:25:53