简体   繁体   中英

React Router 4 passing props through Route render doesn't work

This question has been asked, but other answers aren't solving this for me. I want to pass the signInWithEmail handler function from my <App /> component down through <Layout /> and then to the <SignIn /> component via a <Route /> .

The way to do this is apparently via the render attribute on the Route, but for me it just renders ignores my onSubmit . In React dev tools I just see the default Route props, even though I can see my handler function(s) in the <Layout /> element showing up as props.signInWithEmail . They don't make it to the <SignIn /> element.

What am I missing? Thanks.

const Layout = (props) => (
// i can console.log(props) here and see props.signInWithEmail
  <div className="layout">
    // header etc...
    <main>
      <Switch>
       // ... other routes
        <Route
          path="/signin"
          render= {(props) => <SignIn onSubmit={props.signInWithEmail} />}           
        />
      </Switch>
    </main>
    // footer etc...
  </div>
)}

render part of App:

  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <Layout 
            signInWithEmail={this.signInWithEmail} 
            signUpWithEmail={this.signUpWithEmail} 
            signOut={this.signOut} 
            state={this.state}
          />
        </BrowserRouter>
      </div>
    );
  }

It happens because you overriding props within arrow function. Try to destructure Layout prop like that:

const Layout = ({signInWithEmail}) => (
// i can console.log(props) here and see props.signInWithEmail
  <div className="layout">
    // header etc...
    <main>
      <Switch>
       // ... other routes
        <Route
          path="/signin"
          render= {() => <SignIn onSubmit={signInWithEmail} />}           
        />
      </Switch>
    </main>
    // footer etc...
  </div>
)}

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