javascript - 在Link react-rou中传递道具

我正在使用react-react进行反应。我试图在反应路由器的“链接”中传递属性

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;

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

vishal atmakuri asked 2019-08-06T03:34:24Z
5个解决方案
82 votes

此行缺失// 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'));

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

应该:

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

鉴于以下// 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'));

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

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

给出了像// 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'));这样的路线



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

// 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'));
router.isActive({ pathname, query }, indexOnly)

更新:

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

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

router.isActive({ pathname, query }, indexOnly) ,onEnter和isActive使用位置描述符

router.isActive({ pathname, query }, indexOnly) 现在可以获取除字符串之外的位置描述符。   不推荐使用查询和状态道具。

// v1.0.x

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

// v2.0.0

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

//仍然在2.x中有效

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

同样,从onEnter挂钩重定向现在也使用一个位置  描述。

// v1.0.x

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

// v2.0.0

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

对于类似自定义链接的组件,这同样适用于router.isActive,   以前的历史.isActive。

// v1.0.x

router.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]
jmunsch answered 2019-08-06T03:38:58Z
41 votes

有一种方法可以传递多个参数。 您可以将“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
Chetan Sisodiya answered 2019-08-06T03:39:23Z
34 votes

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

你可以这样做:

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

Alessander França answered 2019-08-06T03:40:07Z
15 votes

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

<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
Kevin K. answered 2019-08-06T03:40:46Z
0 votes

路线:

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

然后可以访问PageCustomer组件中的params,如下所示:this.props.match.params.id

例如,PageCustomer组件中的api调用:

axios({
   method: 'get',
   url: '/api/customers/' + this.props.match.params.id,
   data: {},
   headers: {'X-Requested-With': 'XMLHttpRequest'}
 })
Abu Shumon answered 2019-08-06T03:41:25Z
translate from https://stackoverflow.com:/questions/30115324/pass-props-in-link-react-router