react-router如何通过<links>和<route>将props传递给其他组件?

时间:2016-12-01 03:38:48

标签: javascript reactjs react-router

我有一个select输入来在PageA1中创建一个newCountry的值。我想将此值传递给PageB。但是当我选择newCountry时,控制台会警告:[react-router] You cannot change <Router routes>; it will be ignored

如何使用<Links><Route>传递newCountry的值?

PageA.js:

 export default class PageA extends Component{
      constructor(props){
        super(props);
        this.state = {
          country:''
        }
      }

  // 收取country的callback
  selectCountry = (newCountry)=>{
    this.setState({country:newCountry});
    this.props.callbackPageA(newCountry);
  }

  render(){
    return(
      <div>
        <div>
          <PageA1 callbackCountry={this.selectCountry} />
        </div>
      </div>
    );
  }
}

我的路由器App.js:

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state={
      country:''
    }
  }
  PageAValue = (newCountry) =>{
    this.setState({
      country:newCountry
    })
  }
  render () {
    const CountryProps = this.state.country;
    console.log('app '+CountryProps);
    return(
      <Router history={browserHistory}>
        <Route path="/" component={HomePage}></Route>
        <Route path="/PageA" component={() => <PageA callbackPageA={this.PageAValue}/>}></Route>
        <Route path="/PageB" component={PageB}  CountryProps={CountryProps}>
        </Route>
      </Router>
    )
  }
}

PageB.js:

export default class PageB extends React.Component {
  constructor(props){
    super(props);
  }
  render () {
    const country = this.props.route.CountryProps;
    console.log('corepage ' + country);

    return(
      <div>
        <div>
          <div><PageD country={country}/></div>
        </div>
      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:2)

您可以将状态附加到location descriptor。例如,您可以将to的{​​{1}}道具定义为:

<Link>

然后在<Link to={{ pathname: '/PageB', state: { country: 'Ireland' }}} /> 组件中,PageB将作为prop提供。

location组件纯粹用于配置,实际上并未呈现,这就是您收到警告的原因。