简体   繁体   English

React Router 4通过路由渲染传递道具不起作用

[英]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 /> . 我想通过<Layout /><App />组件向下传递signInWithEmail处理函数,然后通过<Route />传递给<SignIn />组件。

The way to do this is apparently via the render attribute on the Route, but for me it just renders ignores my onSubmit . 这样做的方法显然是通过Route上的render属性,但是对我来说,它只是渲染而忽略了我的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 . 在React开发工具中,即使我可以在<Layout />元素中看到我的处理函数显示为props.signInWithEmail ,我也只能看到默认的Route道具。 They don't make it to the <SignIn /> element. 他们没有进入<SignIn />元素。

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: 呈现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: 尝试像这样破坏Layout属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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