【问题标题】:How can I pass values from a functional component through a React Router Link to another functional component?如何通过 React Router Link 将功能组件中的值传递到另一个功能组件?
【发布时间】:2020-01-08 16:33:36
【问题描述】:

如何使用 React Router 的 Link 组件将值从我的 ResultItem.js 组件传递到我的 Result.js 组件?

ResultItem.js

export default function ResultItem({ result }) {
//desctructure the result elements
const {
    title,
    type,
    id,
    publisher,
    volume,
    issue,
    page_number,
    year_published,
} = result;

return (
    <>
        <div className="card grey lighten-4" style={{ padding: '1rem' }}>
            <span className="badge green white-text">{type}</span>
            <h5>{title}</h5>
            <h6>Publisher: {publisher}</h6>
            <h6>Volume: {volume}</h6>
            <h6>Issue: {issue}</h6>
            <h6>Page Number: {page_number}</h6>
            <h6>Year Published: {year_published}</h6>

            <div>
                <Link
                    to={`/${id}`}
                    className="waves-effect waves-light btn-small blue"
                >
                    Read More
                </Link>
            </div>
        </div>
    </>
);

}

结果.js

export default function Result({ title }) {
return (
    <>
        <div className="container">
            <h5>
                More information about that thing you just clicked on will be on this
                page.
            </h5>
            <h1>title = {title}</h1>
        </div>
    </>
);

}

App.js

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

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:
    <Link to={{ 
           pathname: `/item/${item.id}`,
           state: {id: item.id}
    }}> 
    

    稍后您在结果中调用:{id.id}

    有效吗?

    【讨论】:

    • 不,不幸的是,这只会在Results.js 内部为id 引发未定义的错误。
    • call: {id.id} in Result 是什么意思?
    • 如果添加 - const { match } = props;让 id = match.params;可以通过 {id.id} 调用 id
    猜你喜欢
    • 2021-10-24
    • 2021-02-02
    • 2020-05-27
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多