ChatGPT解决这个技术问题 Extra ChatGPT

在 Link react-router 中传递道具

我正在使用 react-router 进行反应。我正在尝试在 react-router 的“链接”中传递属性

var React  = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');

var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
  render : function(){
    return(
      <div>
        <Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
        <RouteHandler/>
      </div>
    );
  }
});

var routes = (
  <Route name="app" path="/" handler={App}>
    <Route name="ideas" handler={CreateIdeaView} />
    <DefaultRoute handler={Home} />
  </Route>
);

Router.run(routes, function(Handler) {

  React.render(<Handler />, document.getElementById('main'))
});

“链接”呈现页面但不将属性传递给新视图。下面是查看代码

var React = require('react');
var Router = require('react-router');

var CreateIdeaView = React.createClass({
  render : function(){
    console.log('props form link',this.props,this)//props not recived
  return(
      <div>
        <h1>Create Post: </h1>
        <input type='text' ref='newIdeaTitle' placeholder='title'></input>
        <input type='text' ref='newIdeaBody' placeholder='body'></input>
      </div>
    );
  }
});

module.exports = CreateIdeaView;

如何使用“链接”传递数据?


j
jmunsch

此行缺少 path

<Route name="ideas" handler={CreateIdeaView} />

应该:

<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />

鉴于以下 Link (过时的 v1)

<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>

v4/v5 的最新版本:

const backUrl = '/some/other/value'
// this.props.testvalue === "hello"

// Using query
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />

// Using search
<Link to={{pathname: `/${this.props.testvalue}`, search: `?backUrl=${backUrl}`} />
<Link to={`/${this.props.testvalue}?backUrl=${backUrl}`} />

withRouter(CreateIdeaView) 组件 render() 中,withRouter 高阶组件的过时用法:

console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value

在使用 useParamsuseLocation 钩子的功能组件中:

const CreatedIdeaView = () => {
    const { testvalue } = useParams();
    const { query, search } = useLocation(); 
    console.log(testvalue, query.backUrl, new URLSearchParams(search).get('backUrl'))
    return <span>{testvalue} {backurl}</span>    
}

从您在文档上发布的链接到页面底部:

给定一个像 这样的路由

使用一些存根查询示例更新了代码示例:

// import React, {Component, Props, ReactDOM} from 'react'; // 从 'react-router' 导入 {Route, Switch}; etc etc // 此代码段已将其全部附加到窗口,因为它在浏览器中 const { BrowserRouter, Switch, Route, Link, NavLink } = ReactRouterDOM;类 World 扩展 React.Component { constructor(props) { super(props);控制台.dir(道具); this.state = { fromIdeas: props.match.params.WORLD || '未知' } } 渲染() { 常量 { 匹配,位置} = this.props; return (

{this.state.fromIdeas}

thing: {location.query && location.query.thing}
another1: {location.query && location.query.another1 || 'none for 2 or 3'} ); } } 类想法扩展 React.Component { 构造函数(道具) { 超级(道具);控制台.dir(道具); this.state = { fromAppItem: props.location.item, fromAppId: props.location.id, nextPage: 'world1', showWorld2: false } } render() { return (
  • item: {this .state.fromAppItem.okay}
  • id: {this.state.fromAppId}
  • Home 1
  • {this.state.showWorld2 &&
  • Home 2
  • } Home 3
    ); } } 类 App 扩展 React.Component { render() { return ( Ideas ); } } ReactDOM.render(( ), document.getElementById('ideas'));

    #更新:

    请参阅:https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors

    从 1.x 到 2.x 的升级指南:、onEnter 和 isActive 使用位置描述符 现在除了字符串之外还可以使用位置描述符。不推荐使用查询和状态道具。 // v1.0.x // v2.0.0 // 在 2.x 中仍然有效 同样,从 onEnter 挂钩重定向现在也使用位置描述符。 // v1.0.x (nextState, replaceState) => replaceState(null, '/foo') (nextState, replaceState) => replaceState(null, '/foo', { the: 'query' }) // v2 .0.0 (nextState, replace) => replace('/foo') (nextState, replace) => replace({ pathname: '/foo', query: { the: 'query' } }) 用于自定义类链接组件,同样适用于 router.isActive,之前的 history.isActive。 // v1.0.x history.isActive(pathname, query, indexOnly) // v2.0.0 router.isActive({ pathname, query }, indexOnly)

    #v3 到 v4 的更新:

    https://github.com/ReactTraining/react-router/blob/432dc9cf2344c772ab9f6379998aa7d74c1d43de/packages/react-router/docs/guides/migrating.md

    https://github.com/ReactTraining/react-router/pull/3803

    https://github.com/ReactTraining/react-router/pull/3669

    https://github.com/ReactTraining/react-router/pull/3430

    https://github.com/ReactTraining/react-router/pull/3443

    https://github.com/ReactTraining/react-router/pull/3803

    https://github.com/ReactTraining/react-router/pull/3636

    https://github.com/ReactTraining/react-router/pull/3397

    https://github.com/ReactTraining/react-router/pull/3288

    界面基本还是v2一样,最好看一下react-router的CHANGES.md,因为那是更新的地方。

    供后代使用的“遗留迁移文件”

    https://github.com/ReactTraining/react-router/blob/dc7facf205f9ee43cebea9fab710dce036d04f04/packages/react-router/docs/guides/migrating.md

    https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v1.0.0.md

    https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md

    https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.2.0.md

    https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.4.0.md

    https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.5.0.md


    似乎 2.0 版不支持参数,假设测试值存储在道具中,它会类似于 <Link to={/ideas/${this.props.testvalue}}>{this.props.testvalue}</Link>
    @Braulio 谢谢。我更新了我的答案,并包含了更多关于 v1 和 v2 之间 差异的文档
    @Braulio:正确的方法是:<Link to={`/ideas/${this.props.testvalue}`}>{this.props.testvalue}</Link>,带反引号
    是的,抱歉,当我粘贴要修复它的代码时,反引号丢失了。
    这对我有用,不使用反引号 <Link to={'/ideas/'+this.props.testvalue }>{this.props.testvalue}</Link>
    S
    Shivang Patel

    有一种方法可以传递多个参数。您可以将“to”作为对象而不是字符串传递。

    // your route setup
    <Route path="/category/:catId" component={Category} / >
    
    // your link creation
    const newTo = { 
      pathname: "/category/595212758daa6810cbba4104", 
      param1: "Par1" 
    };
    // link to the "location"
    // see (https://reacttraining.com/react-router/web/api/location)
    <Link to={newTo}> </Link>
    
    // In your Category Component, you can access the data like this
    this.props.match.params.catId // this is 595212758daa6810cbba4104 
    this.props.location.param1 // this is Par1
    

    正是我想要的。
    这个答案被低估了。这并不明显,但文档中提到了这个 reacttraining.com/react-router/web/api/Link/to-object。它建议将数据作为标记为“状态”的单个对象传递
    这是这个问题的最佳答案。
    在路径属性中不应该是“/category/595212758daa6810cbba4104”而不是映射到文章???
    这个答案虽然很好,但不适用于 react-router-dom 的 V6。为此,请参阅 this answer
    Z
    Zahidur Rahman Faisal

    我在从我的应用程序中显示用户详细信息时遇到了同样的问题。

    你可以这样做:

    <Link to={'/ideas/'+this.props.testvalue }>Create Idea</Link>
    

    或者

    <Link to="ideas/hello">Create Idea</Link>
    

    <Route name="ideas/:value" handler={CreateIdeaView} />
    

    在您的 CreateIdeaView 类中通过 this.props.match.params.value 获取此信息。

    您可以观看对我有很大帮助的视频:https://www.youtube.com/watch?v=ZBxMljq9GSE


    正是文档所说的。但是,我有一个案例,尽管如上所述定义了 Route,并配置了 LINK 以传递参数值,但 React 组件类没有从 URL 中获取任何 this.props.params 值。知道为什么会发生这种情况吗?就像路由绑定完全丢失一样。组件类中的 render() 确实参与,但没有数据传递到组件中。
    但是在您的最后一个示例中,您如何在 CreateIdeaView 组件中提取“值”变量?
    F
    Farhan

    See this post for reference

    简单的是:

    <Link to={{
         pathname: `your/location`,
         state: {send anything from here}
    }}
    

    现在你想访问它:

    this.props.location.state
    

    这对类组件有用吗,对我来说它不起作用
    @lokesh 是的,您需要将其包装在功能组件中并作为 props 传递
    K
    Kevin K.

    至于 react-router-dom 4.xx (https://www.npmjs.com/package/react-router-dom),您可以将参数传递给组件以通过以下方式路由:

    <Route path="/ideas/:value" component ={CreateIdeaView} />
    

    链接方式(考虑将 testValue 属性传递给渲染链接的相应组件(例如上面的 App 组件))

    <Link to={`/ideas/${ this.props.testValue }`}>Create Idea</Link>
    

    将道具传递给您的组件构造函数,值参数将通过

    props.match.params.value
    

    是的,它很好用 <Link to={/movie/detail/${this.state.id}} className="btn btn-secondary btn-lg active">Detail</Link>
    K
    Krishna Jangid

    安装后 react-router-dom

    <Link
        to={{
          pathname: "/product-detail",
          productdetailProps: {
           productdetail: "I M passed From Props"
          }
       }}>
        Click To Pass Props
    </Link>
    

    和路由重定向的另一端执行此操作

    componentDidMount() {
                console.log("product props is", this.props.location.productdetailProps);
              }
    

    我使用相同的方式 V5 。但在类组件中。但不工作
    g
    gprathour

    打字稿

    对于许多答案中提到的这种方法,

    <Link
        to={{
            pathname: "/my-path",
            myProps: {
                hello: "Hello World"
            }
        }}>
        Press Me
    </Link>
    

    我遇到了错误,

    对象字面量只能指定已知属性,并且类型 'LocationDescriptorObject | 中不存在 'myProps' ((位置:位置)=> LocationDescriptor)'

    然后我签入了他们为相同目的提供的 stateofficial documentation

    所以它是这样工作的,

    <Link
        to={{
            pathname: "/my-path",
            state: {
                hello: "Hello World"
            }
        }}>
        Press Me
    </Link>
    

    在您的下一个组件中,您可以获得以下值,

    componentDidMount() {
        console.log("received "+this.props.location.state.hello);
    }
    

    F
    FBaez51

    要解决上面的答案 (https://stackoverflow.com/a/44860918/2011818),您还可以将对象内嵌在 Link 对象内的“To”中。

    <Route path="/foo/:fooId" component={foo} / >
    
    <Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
    
    this.props.match.params.fooId //newb
    this.props.location.sampleParam //"Hello"
    this.props.location.sampleParam2 //"World!"
    

    Z
    Zayne komichi

    在您的 Link 组件中执行状态

    <Link to='register' state={{name:'zayne'}}>
    

    现在要访问您访问的页面中的项目,请导入 useLocation

    import {useLocation} from 'react-router-dom';
    
    const Register=()=>{
    
    const location = useLocation()
    
    //store the state in a variable if you want 
    //location.state then the property or object you want
    
    const Name = location.state.name
    
    return(
      <div>
        hello my name is {Name}
      </div>
    )
    
    }
    
    

    A
    Anand Kapdi

    对于 v5

     <Link
      to={{
        pathname: "/courses",
        search: "?sort=name",
        hash: "#the-hash",
        state: { fromDashboard: true }
      }}
    />
    

    React Router Official Site


    a
    alex-adestech.mx

    就我而言,我有一个带有空道具的功能组件,这解决了它:

    <Link
      to={{
        pathname: `/dashboard/${device.device_id}`,
        state: { device },
      }}
    >
      View Dashboard
    </Link>
    

    在你的函数组件中,你应该有这样的东西:

    import { useLocation } from "react-router"
    export default function Dashboard() {
      const location = useLocation()
      console.log(location.state)
      return <h1>{`Hello, I'm device ${location.state.device.device_id}!`}</h1>
    }
    

    R
    RameshD

    最简单的方法是使用文档中提到的 link 中的 to:object
    https://reactrouter.com/web/api/Link/to-object

    <Link
      to={{
        pathname: "/courses",
        search: "?sort=name",
        hash: "#the-hash",
        state: { fromDashboard: true, id: 1 }
      }}
    />
    
    

    我们可以检索上述参数(状态),如下所示:

    this.props.location.state // { fromDashboard: true ,id: 1 }
    

    K
    KFunk

    如果您只是想替换路线中的 slug,您可以使用 generatePathwas introduced in react-router 4.3 (2018)。到今天为止,它还没有包含在 react-router-dom (web) documentation 中,而是包含在 react-router (core) 中。 Issue#7679

    // myRoutes.js
    export const ROUTES = {
      userDetails: "/user/:id",
    }
    
    
    // MyRouter.jsx
    import ROUTES from './routes'
    
    <Route path={ROUTES.userDetails} ... />
    
    
    // MyComponent.jsx
    import { generatePath } from 'react-router-dom'
    import ROUTES from './routes'
    
    <Link to={generatePath(ROUTES.userDetails, { id: 1 })}>ClickyClick</Link>
    

    这与 django.urls.reverse 已有一段时间的概念相同。


    M
    Maruf

    对于 v6: 注意! state 应该在 to={} 之外

    // route setup
    <Route path="/employee-edit/:empId" element={<EmployeeEdit />} / >
    

    Link 到组件

    <Link to={"/employee-edit/1"} state={{ data: employee }} > Edit </Link>
    

    或者

    <Link to={{
           pathname: "/employee-edit/1",
           search: "?sort=name",
           hash: "#the-hash",
         }}
           state={{ data: employee }} > Edit </Link>
    

    注意: stateto{} 之外,但对于 v5

    <Link
      to={{
        pathname: "/courses",
        search: "?sort=name",
        hash: "#the-hash",
        state: { fromDashboard: true }
      }}
    />
              
    

    功能组件:

    import React from "react";
    import { useLocation } from "react-router-dom";
    
    const LinkTest = () => {
      const location = useLocation();
      console.log("Location", location);
      return <h1>Link Test</h1>;
    };
    
    export default LinkTest;
    

    类组件:为了使用钩子,我们需要将其包装在功能组件中并传递道具:

    import React, { Component } from "react";
    import { useLocation, useParams } from "react-router-dom";
    
    class LinkTestComponent extends Component {
      render() {
        console.log(this.props);
        return <h1>Link Test</h1>;
      }
    }
    
    export default () => (
      <LinkTestComponent params={useParams()} location={useLocation()} />
    );
    

    测试: "react-router-dom": "^6.2.2",


    e
    eanmos

    我为此苦苦挣扎了几个小时,但这个主题中没有一个答案对我有用。最后,我设法在 documentation 中找到了 React Router 6 的解决方案。

    这是完整的示例:

    // App.js
    
    <BrowserRouter>
        <Routes>
            <Route path="/books/:bookId" element={ <BookDetails /> } />
        </Routes>
    </BrowserRouter>
    
    // BookDetails.js
    
    import React from "react"
    import { useParams } from "react-router-dom"
    
    export default function BookPage() {
        const params = useParams()
        return <div> { console.log(params.bookId) } </div>
    }
    

    请注意,useParams 不能在类组件内调用,因此您必须使用函数组件(有关详细信息,请参阅 this 答案)。


    A
    Abu Shumon

    路线:

    <Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />
    

    然后可以像这样访问 PageCustomer 组件中的参数:this.props.match.params.id

    例如 PageCustomer 组件中的 api 调用:

    axios({
       method: 'get',
       url: '/api/customers/' + this.props.match.params.id,
       data: {},
       headers: {'X-Requested-With': 'XMLHttpRequest'}
     })
    

    c
    c-sharp-and-swiftui-devni

    更新 25-11-21 感谢上面写的 alex-adestech.mx。我能够传输整个对象并在 send-component 中从中提取所有必要的字段:

    <Button type="submit" component={NavLink} to={{
            pathname: '/basequestion',
            state: {question} }}
            variant="contained"
            size="small">Take test</Button>
    

    在接收组件中:

    import { useLocation } from "react-router"
    const BaseQuestion = () => {
    const location = useLocation();
    const {description, title, images} = (location.state.question);