在Link react-router中传递道具


137

我正在使用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;

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

Answers:


123

此行缺失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起最新

const backUrl = '/some/other/value'
// this.props.testvalue === "hello"
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />

并在withRouter(CreateIdeaView)组件中render()

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

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

给定一条路线 <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

从1.x到2.x的升级指南:

<Link to>,onEnter和isActive使用位置描述符

<Link to>现在可以使用除字符串之外的位置描述符。查询和状态道具已弃用。

// v1.0.x

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

// v2.0.0

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

//在2.x版本中仍然有效

<Link to="/foo"/>

同样,从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的更新:

后代的“旧版迁移文档”


3
似乎2.0版不支持params,假设测试值存储在props中,则类似于<Link to = { /ideas/${this.props.testvalue}}> {this.props.testvalue} </ Link>
Braulio

1
@Braulio谢谢。我更新了答案,并包含了更多文档,以了解v1和v2之间<Link>的区别
jmunsch

4
@Braulio:正确的方法是:<Link to={`/ideas/${this.props.testvalue}`}>{this.props.testvalue}</Link>带反引号
Enoah Netzach

1
是的,很抱歉,当我粘贴要修复的代码时,反引号迷路了。
Braulio

2
这对我有效,而无需使用反引号<Link to={'/ideas/'+this.props.testvalue }>{this.props.testvalue}</Link>
svassr

91

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

2
正是我想要的
gramcha '18 -4-9

8
这个答案被低估了。这并不明显,但是文档中提到了此reacttraining.com/react-router/web/api/Link/to-object。它建议将数据作为标记为“状态”的单个对象进行传递
sErVerdevIL '18

13
这是对这个问题的最佳答案。
胡安·里卡多

与戏剧打交道已经太久了,这完全有效!V4
Mike

1
在路径属性中不应为“ / category / 595212758daa6810cbba4104”,而不是映射到商品?
卡米洛

38

我有同样的问题要显示我的应用程序中的用户详细信息。

你可以这样做:

<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.valueCreateIdeaView类获得此信息。

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


3
正是文档所说的。但是,我有一种情况,尽管DESPITE定义了上述Route,并配置LINK以传递参数值,但是React组件类没有从URL中获取任何this.props.params值。知道为什么会发生这种情况吗?就像路由绑定完全丢失一样。组件类中的render()确实参与,但是没有数据传递到组件中。
彼得

但是,在最后一个示例中,然后如何在CreateIdeaView组件中提取'value'变量?
阿斯彭

20

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

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

通过链接(考虑将testValue属性传递给呈现链接的相应组件(例如,上面的App组件))

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

将props传递给组件构造函数,可以通过以下方式使用value参数

props.match.params.value


7

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

4

要解决以上答案(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!"

3

打字稿

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

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

我遇到错误了

对象文字只能指定已知的属性,而'myProps'在'LocationDescriptorObject |类型中不存在。((位置:位置=> LocationDescriptor)'

然后我检查了他们提供的官方文件state出于相同目的。

所以它像这样工作

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

在下一个组件中,您可以按以下方式获得此值,

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

谢谢@gprathour
Akshay Vijay Jain

0

路线:

<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'}
 })
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.