반응 라우터와 반응하고 있습니다. 반응 라우터의 “링크”에 속성을 전달하려고합니다.
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;
“링크”를 사용하여 데이터를 전달하려면 어떻게해야합니까?
답변
이 줄이 없습니다 path:
<Route name="ideas" handler={CreateIdeaView} />
해야한다:
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
다음과 같은 Link (구식 v1) :
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
v4부터 최신 :
const backUrl = '/some/other/value'
// this.props.testvalue === "hello"
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />
그리고 withRouter(CreateIdeaView)구성 요소에서 render():
console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value
문서에 게시 한 링크에서 페이지 하단으로 :
다음과 같은 경로가 주어집니다.
<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>
업데이트 :
1.x에서 2.x 로의 업그레이드 안내서에서 :
<Link to>, onEnter 및 isActive 사용 위치 설명자
<Link to>문자열 외에도 위치 설명자를 사용할 수 있습니다. 쿼리 및 상태 소품은 더 이상 사용되지 않습니다.// v1.0.x
<Link to="/foo" query={{ the: 'query' }}/>// v2.0.0
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>// 2.x에서 여전히 유효
<Link to="/foo"/>마찬가지로 onEnter 후크에서 경로 재 지정에도 위치 디스크립터가 사용됩니다.
// 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' } })사용자 지정 링크와 같은 구성 요소의 경우 router.isActive, 이전 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/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
 
답변
둘 이상의 매개 변수를 전달할 수있는 방법이 있습니다. 문자열 대신 “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={'/ideas/'+this.props.testvalue }>Create Idea</Link>
또는
<Link to="ideas/hello">Create Idea</Link>
과
<Route name="ideas/:value" handler={CreateIdeaView} />
this.props.match.params.valueCreateIdeaView 클래스 를 통해 얻을 수 있습니다.
https://www.youtube.com/watch?v=ZBxMljq9GSE에 많은 도움이 된이 비디오를 볼 수 있습니다
답변
react-router-dom 4.xx ( https://www.npmjs.com/package/react-router-dom )의 경우 매개 변수를 구성 요소에 전달하여 다음을 통해 라우팅 할 수 있습니다.
<Route path="/ideas/:value" component ={CreateIdeaView} />
연결을 통해 연결 (testValue 소품을 고려하면 해당 구성 요소 (예 : 위의 App 구성 요소)로 전달되어 링크가 렌더링 됨)
<Link to={`/ideas/${ this.props.testValue }`}>Create Idea</Link>
소품을 컴포넌트 생성자에 전달하면 value param을 통해 사용할 수 있습니다.
props.match.params.value
답변
간단합니다 :
<Link to={{
     pathname: `your/location`,
     state: {send anything from here}
}}
이제 당신은 그것에 접근하고 싶습니다 :
this.props.location.state
답변
설치 후 react-router-dom
<Link
    to={{
      pathname: "/product-detail",
      productdetailProps: {
       productdetail: "I M passed From Props"
      }
   }}>
    Click To Pass Props
</Link>
경로가 리디렉션되는 다른 쪽 끝
componentDidMount() {
            console.log("product props is", this.props.location.productdetailProps);
          }
답변
위의 답변 ( https://stackoverflow.com/a/44860918/2011818 )을 해결하기 위해 Link 객체 내부의 “To”인라인으로 객체를 보낼 수도 있습니다.
<Route path="/foo/:fooId" component={foo} / >
<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"
