简体   繁体   中英

Why can't I pass this prop to the child component?

I've been having a problem with React Route. I can pass pass2Parent={this.pass2Parent} to the Search component, but I can't pass data={data} to the Result component.

I've been researching the problem for hours and I've explored using render instead of component in the route. Unfortunately, it had the side effect of calling an API multiple times and burning through my allowance.

I just don't get why it's not working as it is..

render() {
  let data = this.state;
  console.log(data);

  return (
    <div style={{height: "inherit"}}>
      <BrowserRouter>
        <Switch>
          <Route path='/' exact component={() => <Search pass2Parent={this.pass2Parent}/>}/>
          <Route path='/result' exact component={(data) => <Result data={data}/>}/>
        </Switch>
      </BrowserRouter>
    </div>
  );
};

This is what console.log(data) returns:

{
  images: {total: 8327, total_pages: 833, results: Array(10)},
  weather: {coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
}

This is what console.log(this.props) looks like in the child component:

{
  data: {
    history: {length: 2, action: "POP", location: {…}, createHref: ƒ, push: ƒ, …},
    location: { pathname: "/result", search: "", hash: "", state: undefined },
    match: { path: "/result", url: "/result", isExact: true, params: {…} },
    staticContext: undefined,
  }
}

the argument data passed into your component={(data)=> is a SyntheticEvent, that inside it scope overwrite the data value from state. Delete the argument and that it...


<Route path='/result' exact component={() => <Result data={data}/>}/>

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