首页 > 解决方案 > React:如何从React 路由器传递道具?

问题描述

我正在使用 Hacker News API,现在我可以Comments.js使用 URL 中的故事 ID 链接到我,如下所示

export default function Story ({storyID}) {

const [story, setStory] = useState({});

 useEffect(()=> {

    getStoryTitle(storyID).then(data => data && data.url && setStory(data));
 });

    const kids = story.kids ? story.kids: [];
     const author = story.by;
        return (

          <div className="story-wrapper">

             <a className="a-tag" href={story.url}>
               <p className="story-title">{story.title}</p>
             </a>
             <p className="story-author"><strong>By: {story.by}</strong> on {timeFormat(story.time)}</p>
             <p className="story-comments"><Link to={`/comments/${storyID}`}>{kids.length}</Link> Comments</p>
             {

编辑:我Comments.js喜欢这样

    import React, {useState, useEffect} from 'react'
import {getStoryTitle} from '../API.js'
const {comment}
export default function Comments({storyID}) {
    const [comment, setComment] = useState({});


    useEffect(()=> {
        getStoryTitle(storyID).then(data => setComment(data))
    }, [])

    return (
        <ul>
            <li>{storyID}</li>
        </ul>
    )
}

我需要知道如何在我的Comments.js组件中呈现数据,类似于我使用在 url 上传递的道具来处理故事标题和作者的方式。

标签: reactjsreact-router

解决方案


匹配

给定评论路由路径定义为,从proppath="/comments/:commentId"访问 id 。match

this.props.match.params.commentId

地点

如果您需要通过路由推送发送状态,它会在链接的toprop 中作为指定pathname和的对象state发送到新路由。

to={{ pathname: `/comments/${storyID}`, state: { data } }}

location道具访问。

this.props.location.state.data

数据可以是任何有效的对象有效载荷

编辑

假设Comments呈现如下:

<Route path="/comments/:id" component={Comments} />

id然后从收到的match道具中解压:

import React, { useState, useEffect } from 'react';
import { getStoryTitle } from '../API.js';

export default function Comments({ match }) {
  const { id } = match.params;
  const [comment, setComment] = useState({});

  useEffect(()=> {
    getStoryTitle(id).then(data => setComment(data));
  }, []);

  return (
    <ul>
      <li>{id}</li>
    </ul>
  );
}

推荐阅读