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

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


当前回答

更新25-11-21 感谢alexadestech。Mx在上面写道。 我能够转移整个对象,并从中抽出所有必要的字段 在send-component中:

<Button type="submit" component={NavLink} to={{
        pathname: '/basequestion',
        state: {question} }}
        variant="contained"
        size="small">Take test</Button>

在receive-component:

import { useLocation } from "react-router"
const BaseQuestion = () => {
const location = useLocation();
const {description, title, images} = (location.state.question);

其他回答

我为此挣扎了几个小时,没有一个答案对我有用。最后,我设法在文档中找到了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组件中执行状态

<Link to='register' state={{name:'zayne'}}>

现在要访问页面中的项目,导入useLocation

import {useLocation} from 'react-router-dom';

const Register=()=>{

const location = useLocation()

//store the state in a variable if you want 
//location.state then the property or object you want

const Name = location.state.name

return(
  <div>
    hello my name is {Name}
  </div>
)

}

如果你只是想替换路由中的蛞蝓,你可以使用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一段时间以来的概念是一样的。

打印稿

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

<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