在 Link react-router 中传递道具

Pass props in Link react-router

我正在使用 react 和 react-router。 我正在尝试在反应路由器

的 "Link" 中传递 属性
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'))
});

"Link" 呈现页面但不将 属性 传递到新视图。 下面是查看代码

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;

如何使用 "Link" 传递数据?

缺少这一行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>    
}

来自您在文档上发布的 link,页面底部:

Given a route like <Route name="user" path="/users/:userId"/>



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

// import React, {Component, Props, ReactDOM} from 'react';
// import {Route, Switch} from 'react-router'; etc etc
// this snippet has it all attached to window since its in browser
const {
  BrowserRouter,
  Switch,
  Route,
  Link,
  NavLink
} = ReactRouterDOM;

class World extends React.Component {
  constructor(props) {
    super(props);
    console.dir(props);      
    this.state = {
      fromIdeas: props.match.params.WORLD || 'unknown'
    }
  }
  render() {
    const { match, location} = this.props;
    return (
      <React.Fragment>
        <h2>{this.state.fromIdeas}</h2>
        <span>thing: 
          {location.query 
            && location.query.thing}
        </span><br/>
        <span>another1: 
        {location.query 
          && location.query.another1 
          || 'none for 2 or 3'}
        </span>
      </React.Fragment>
    );
  }
}

class Ideas extends React.Component {
  constructor(props) {
    super(props);
    console.dir(props);
    this.state = {
      fromAppItem: props.location.item,
      fromAppId: props.location.id,
      nextPage: 'world1',
      showWorld2: false
    }
  }
  render() {
    return (
      <React.Fragment>
          <li>item: {this.state.fromAppItem.okay}</li>
          <li>id: {this.state.fromAppId}</li>
          <li>
            <Link 
              to={{
                pathname: `/hello/${this.state.nextPage}`, 
                query:{thing: 'asdf', another1: 'stuff'}
              }}>
              Home 1
            </Link>
          </li>
          <li>
            <button 
              onClick={() => this.setState({
              nextPage: 'world2',
              showWorld2: true})}>
              switch  2
            </button>
          </li>
          {this.state.showWorld2 
           && 
           <li>
              <Link 
                to={{
                  pathname: `/hello/${this.state.nextPage}`, 
                  query:{thing: 'fdsa'}}} >
                Home 2
              </Link>
            </li> 
          }
        <NavLink to="/hello">Home 3</NavLink>
      </React.Fragment>
    );
  }
}


class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Link to={{
          pathname:'/ideas/:id', 
          id: 222, 
          item: {
              okay: 123
          }}}>Ideas</Link>
        <Switch>
          <Route exact path='/ideas/:id/' component={Ideas}/>
          <Route path='/hello/:WORLD?/:thing?' component={World}/>
        </Switch>
      </React.Fragment>
    );
  }
}

ReactDOM.render((
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('ideas'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.3.1/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.3.1/react-router.min.js"></script>

<div id="ideas"></div>

#更新:

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

From the upgrade guide from 1.x to 2.x:

<Link to>, onEnter, and isActive use location descriptors

<Link to> can now take a location descriptor in addition to strings. The query and state props are deprecated.

// v1.0.x

<Link to="/foo" query={{ the: 'query' }}/>

// v2.0.0

<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>

// Still valid in 2.x

<Link to="/foo"/>

Likewise, redirecting from an onEnter hook now also uses a location descriptor.

// 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' } })

For custom link-like components, the same applies for router.isActive, previously history.isActive.

// v1.0.x

history.isActive(pathname, query, indexOnly)

// v2.0.0

router.isActive({ pathname, query }, indexOnly)

#v3 到 v4 的更新:

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

后代的“遗留迁移文档”

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

你可以这样做:

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

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

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

通过 this.props.match.params.value 在您的 CreateIdeaView class 中获取此内容 class。

你可以看到这个对我帮助很大的视频:https://www.youtube.com/watch?v=ZBxMljq9GSE

对于 react-router-dom 4.x.x (https://www.npmjs.com/package/react-router-dom) 你可以将参数传递给要路由到的组件:

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

link 通过(考虑将 testValue 属性传递给相应的组件(例如上面的 App 组件)渲染 link)

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

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

可用
props.match.params.value

有一种方法可以传递多个参数。您可以将 "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

路线:

<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'}
 })

安装后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);
          }

要计算出上面的答案 (),您还可以将对象内联到 "To" 内嵌在 Link 对象中。

<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!"

See this post for reference

简单的是:

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

现在您要访问它:

this.props.location.state

打字稿

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

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

我遇到了错误,

Object literal may only specify known properties, and 'myProps' does not exist in type 'LocationDescriptorObject | ((location: Location) => LocationDescriptor)'

然后我查看了他们提供的 official documentation 出于相同目的 state

所以它是这样工作的,

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

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

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

最简单的方法是在 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 }

对于 v5

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

React Router Official Site

如果您只是想替换路线中的 slug,您可以使用 generatePathwas introduced in react-router 4.3 (2018). As of today, it isn't included in the react-router-dom (web) documentation, but is in 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 已经有一段时间的概念相同。

在我的例子中,我有一个带有空 props 的函数组件,这解决了它:

<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>
}

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

<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);

我为此苦苦挣扎了几个小时,但这个主题中没有一个答案对我有用。最后,我设法在 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 无法在 class 组件内部调用,因此您必须使用函数组件(有关详细信息,请参阅 答案)。

在您的 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>
)

}

对于 v6:

// 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;

Class Component: 为了使用 hooks,我们需要将它包装在功能组件中并传递 props:

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",