简体   繁体   中英

Passing state from one React Component to another

I am very new to React (3 days of experience)

I want to pass a date from one component to another but this does not work for me.

What I implemented so far:

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}
...
...

What I expected:

I expected that the date variable is accessible from within the Form component.

The actual result:

TypeError: this.props.location is undefined

you should pass props to component to access it inside the component. in you case where you have mentioned

<Form location = "some value" />

this allows you to access location props in side the Form component using {this.props.location}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM