在 Link react-router 中传递道具 [英] Pass props in Link react-router

查看:21
本文介绍了在 Link react-router 中传递道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-router.我正在尝试在 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({渲染:函数(){返回(<div><Link to="ideas" params={{ testvalue: "hello" }}>创建创意</Link><RouteHandler/>

);}});无功路线 = (<Route name="app" path="/" handler={App}><Route name="ideas" handler={CreateIdeaView}/><DefaultRoute handler={Home}/></路线>);Router.run(路由,函数(处理程序){React.render(, document.getElementById('main'))});

链接"呈现页面,但不会将属性传递给新视图.下面是查看代码

var React = require('react');var Router = require('react-router');var CreateIdeaView = React.createClass({渲染:函数(){console.log('props form link',this.props,this)//没有收到道具返回(<div><h1>创建帖子:</h1><input type='text' ref='newIdeaTitle' placeholder='title'></input><input type='text' ref='newIdeaBody' placeholder='body'></input>

);}});module.exports = CreateIdeaView;

如何使用链接"传递数据?

解决方案

缺少这一行 path:

应该是:

给定以下 Link (过时的 v1):

最新的 v4/v5:

const backUrl = '/some/other/value'//this.props.testvalue === "你好";//使用查询<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}}/>//使用搜索<Link to={{pathname: `/${this.props.testvalue}`,搜索:`?backUrl=${backUrl}`}/><链接到={`/${this.props.testvalue}?backUrl=${backUrl}`}/>

withRouter(CreateIdeaView)组件render()withRouter高阶的过时用法组件:

console.log(this.props.match.params.testvalue, this.props.location.query.backurl)//输出你好/一些/其他/价值

并在使用 useParamsuseLocation 钩子的功能组件中:

const CreatedIdeaView = () =>{const { testvalue } = useParams();const { 查询,搜索 } = useLocation();console.log(testvalue, query.backUrl, new URLSearchParams(search).get('backUrl'))返回 <span>{testvalue} {backurl}</span>}

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

<块引用>

给定一个类似于



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

//从 'react' 导入 React, {Component, Props, ReactDOM};//从 'react-router' 导入 {Route, Switch};等等等等//此代码段已将其全部附加到窗口中,因为它在浏览器中常量{浏览器路由器,转变,路线,关联,导航链接} = ReactRouterDOM;class World 扩展 React.Component {构造函数(道具){超级(道具);控制台目录(道具);this.state = {fromIdeas: props.match.params.WORLD ||'未知'}}使成为() {const { 匹配,位置} = this.props;返回 (<React.Fragment><h2>{this.state.fromIdeas}</h2><span>事情:{location.query&&location.query.thing}</span><br/><span>another1:{location.query&&location.query.another1||'无 2 或 3'}</span></React.Fragment>);}}class Ideas 扩展 React.Component {构造函数(道具){超级(道具);控制台目录(道具);this.state = {fromAppItem: props.location.item,fromAppId: props.location.id,nextPage: 'world1',showWorld2:假}}使成为() {返回 (<React.Fragment><li>项目:{this.state.fromAppItem.okay}</li><li>id:{this.state.fromAppId}</li><li><链接到={{路径名:`/hello/${this.state.nextPage}`,查询:{东西:'asdf',another1:'东西'}}}>首页1</链接><li><按钮onClick={() =>this.setState({nextPage: 'world2',showWorld2: true})}>开关2{this.state.showWorld2&&<li><链接到={{路径名:`/hello/${this.state.nextPage}`,查询:{东西:'fdsa'}}} >家 2</链接>}<NavLink to="/hello">首页 3</NavLink></React.Fragment>);}}类 App 扩展了 React.Component {使成为() {返回 (<React.Fragment><链接到={{路径名:'/ideas/:id',编号:222,物品: {好的:123}}}>想法</Link><开关><路由精确路径='/ideas/:id/' component={Ideas}/><路由路径='/hello/:WORLD?/:thing?'组件={世界}/></开关></React.Fragment>);}}ReactDOM.render((<浏览器路由器><应用程序/></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-active-onenter-and-is位置描述符

<块引用>

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

、onEnter 和 isActive 使用位置描述符

现在除了字符串之外还可以使用位置描述符.不推荐使用查询和状态道具.

//v1.0.x

//v2.0.0

//在 2.x 中仍然有效

同样,从 onEnter 钩子重定向现在也使用位置描述符.

//v1.0.x

(nextState, replaceState) =>替换状态(空,'/foo')(nextState, replaceState) =>replaceState(null, '/foo', { the: 'query' })

//v2.0.0

(nextState, replace) =>替换('/foo')(nextState, 替换) =>替换({路径名:'/foo',查询:{该:'查询'}})

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

//v1.0.x

history.isActive(pathname, query, indexOnly)

//v2.0.0

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

#updates for v3 到 v4:

界面基本还是和v2一样,最好看react-router的CHANGES.md,那里是更新的地方.

遗留迁移文档"为子孙后代

I am using react with react-router. I am trying to pass property’s in a "Link" of 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'))
});

The "Link" renders the page but does not pass the property to the new view. Below is the view code

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;

How can I pass data using "Link"?

解决方案

This line is missing path:

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

Should be:

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

Given the following Link (outdated v1):

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

Up to date as of 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}`} />

and in the withRouter(CreateIdeaView) components render(), out dated usage of withRouter higher order component:

console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value

And in a functional components using the useParams and useLocation hooks:

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

From the link that you posted on the docs, towards the bottom of the page:

Given a route like <Route name="user" path="/users/:userId"/>



Updated code example with some stubbed query examples:

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

#updates:

See: 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)

#updates for v3 to v4:

The interface is basically still the same as v2, best to look at the CHANGES.md for react-router, as that is where the updates are.

"legacy migration documentation" for posterity

这篇关于在 Link react-router 中传递道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆