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

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

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


当前回答

有一种方法可以传递多个参数。你可以传递"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 name="ideas" handler={CreateIdeaView} />

应该是:

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

给定以下链接(过时的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

在使用useParams和useLocation钩子的函数组件中:

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

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

给定一条路由,如< 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:

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一样,最好看看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

我为此挣扎了几个小时,没有一个答案对我有用。最后,我设法在文档中找到了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不能在类组件中调用,因此必须使用函数组件(详细信息请参阅此回答)。

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

你可以这样做:

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

or

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

and

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

在CreateIdeaView类中通过this.props.match.params.value来获取。

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

打印稿

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

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

我得到了错误,

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

然后我查看了他们为同样目的提供的官方文件。

它是这样工作的,

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

在你的下一个组件中,你可以得到如下的值,

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

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