在Link react-router中传递道具

时间:2015-05-08 03:35:15

标签: javascript reactjs react-router

我正在使用react-react进行反应。 我试图在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;

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

12 个答案:

答案 0 :(得分:84)

此行缺少path

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

应该是:

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

鉴于以下Link

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

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

  

给出像<Route name="user" path="/users/:userId"/>

这样的路线


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

&#13;
&#13;
// 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'));
&#13;
<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>
&#13;
&#13;
&#13;

更新

请参阅: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,   以前的历史.isActive。

     

// v1.0.x

history.isActive(pathname, query, indexOnly)
     

// v2.0.0

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

v3到v4的更新:

&#34;旧版迁移文档&#34;后代

答案 1 :(得分:44)

有一种方法可以传递多个参数。你可以将&#34;传递给&#34;作为对象而不是字符串。

// 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 :(得分:34)

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

你可以这样做:

<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

答案 3 :(得分:16)

对于react-router-dom 4.x.x(https://www.npmjs.com/package/react-router-dom),您可以将params传递给组件以路由到:

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

链接via(考虑将testValue prop传递给相应的组件(例如上面的App组件)呈现链接)

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

将props传递给组件构造函数,值param将通过

提供
props.match.params.value

答案 4 :(得分:3)

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

答案 5 :(得分:2)

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

答案 6 :(得分:2)

See this post for reference

简单的是:

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

现在您要访问它:

this.props.location.state

答案 7 :(得分:1)

对于v5

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

React Router Official Site

答案 8 :(得分: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'}
 })

答案 9 :(得分:0)

打字稿

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

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

我遇到了错误,

  

对象文字只能指定已知的属性,而'myProps'在'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);
}

答案 10 :(得分:0)

最简单的方法是使用to:object中的link,如文档中所述:
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 }

答案 11 :(得分:0)

如果您只是想替换路线中的子弹,可以使用generatePath代替was 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已有一段时间的概念相同。