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

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


当前回答

如果你只是想替换路由中的蛞蝓,你可以使用react-router 4.3(2018)中引入的generatePath。到目前为止,它还没有包含在react-router-dom (web)文档中,但在react-router (core)中。问题# 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一段时间以来的概念是一样的。

其他回答

路线:

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

然后可以像这样访问PageCustomer组件中的参数:

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

axios({
   method: 'get',
   url: '/api/customers/' + this.props.match.params.id,
   data: {},
   headers: {'X-Requested-With': 'XMLHttpRequest'}
 })

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

在我的情况下,我有一个空道具的功能组件,这解决了它:

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

对于v6:注意!状态应该在from to={}之外

// route setup
<Route path="/employee-edit/:empId" element={<EmployeeEdit />} / >

链接到组件

<Link to={"/employee-edit/1"} state={{ data: employee }} > Edit </Link>

or

<Link to={{
       pathname: "/employee-edit/1",
       search: "?sort=name",
       hash: "#the-hash",
     }}
       state={{ data: employee }} > Edit </Link>

注意:state在from{}之外,但是for 版本5:

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

Funtional组件:

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;

类组件:为了使用钩子,我们需要将它包装在功能组件中,并传递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"测试,

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