【问题标题】:Passing state from one React Component to another将状态从一个 React 组件传递到另一个
【发布时间】:2018-05-14 09:51:09
【问题描述】:

我是 React 新手(3 天经验)

我想将日期从一个组件传递到另一个组件,但这对我不起作用。

到目前为止我实现了什么:

export class Kurse extends React.Component {
constructor(props) {
  super(props);
}


numbers = ["21.02.2019", "02.05.2018", "13.03.2018", "04.07.2018", "05.08.2018"];
listItems = this.numbers.map((date) =>
  <p><Link to={{pathname: "/bookCourse/"+date}}><Button>{date}</Button></Link></p>
);
render() {
  return(
    <div>
      <h2>Wähle Deinen Wunschtermin</h2>
      {this.listItems}
    </div>
  );
 }
} 

ReactDOM.render(
  <BrowserRouter>
      <Switch>
          <Route path="/" exact render = { () => <Home/>} />
          <Route path="/cityChoice" exact render = { () => <CityChoice/>} />
          <Route path="/kurse" exact render = { () => <Kurse/>}/>
          <Route path='/kjhkhkhkh-spezialisten' component={() => window.location = 'http://kjhkhkhkh-spezialisten.de'}/>
          <Route path='/bookCourse/:date' exact render = { () => <Form/>} />            
      </Switch>
  </BrowserRouter>,
  document.getElementById('root')
)

export class Form extends React.Component{
  constructor(props){
    super(props);

    this.state = {
        vorname: '',
        nachname: '',
        email: '',
        telefon: '',
        refbeginn: 'nächstes Jahr',
        schulart: 'grundschule'
    };
}

...
...

return (
    <div id="form_container">
     {this.props.location.params.date}
...
...

我的预期:

我希望可以从表单组件中访问日期变量。

实际结果:

TypeError: this.props.location 未定义

【问题讨论】:

标签: javascript reactjs properties


【解决方案1】:

您应该将 props 传递给组件以在组件内部访问它。在你提到的情况下

<Form location = "some value" />

这允许您使用 {this.props.location} 访问表单组件中的位置道具。

【讨论】:

  • 你的意思是在路由部分吗?
    } /> ?
  • 如果你想访问路径中的日期,我的意思是从 /bookCourse/:date 访问这个变量,你可以直接使用 this.props.params.date。如果你想获取日期作为单独的道具,那么你可以在
    中传递它,你可以通过 this.props.location
    使用它
  • 好的。我选择使用选项一(通过 URI 中的路径传递它)。不幸的是它仍然说 TypeError: this.props.params is undefined :-(
  • 对 this.props 做一个控制台日志,看看你到底从哪里得到了值并使用那个路径。
  • 我对 this.props 做了一个 console.log,结果是一个空对象 {}。我不知道为什么它是空的。
猜你喜欢
  • 2021-01-11
  • 2019-12-11
  • 2020-03-12
  • 2021-01-02
  • 1970-01-01
  • 2018-09-28
  • 2018-11-03
  • 2018-03-07
  • 2018-09-12
相关资源
最近更新 更多