【问题标题】:Passing Routeing related props to component not rendered by <Route>将路由相关的道具传递给 <Route> 未呈现的组件
【发布时间】:2018-08-25 04:34:28
【问题描述】:

我有一个仪表板组件:

class DashboardPage extends Component {
  ....

  render() {
    const currentLocationPath = this.props.location.pathname;
    const isAuthenticated = true;

    // redirecting to /dashboard/main and saving current state to next path by pushing it to history object
    if (currentLocationPath === '/dashboard/' || currentLocationPath === '/dashboard') {
      this.props.history.push('/dashboard/main');
    }
    const { match } = this.props;

    if (isAuthenticated) {
      return (
        <div className="DashboardPage d-flex flex-column flex-grow">

          {/* email confirmation message for loggedin user to verify email ID*/}
          {!this.state.isEmailVerified ? <div className="email-confirmation">
            <span className="email-confirmation__desktop">
              Please check your inbox to confirm your email <strong>{'loggedin user\'s email'}</strong>.
            Didn’t receive an email? </span>
            <span className="email-confirmation__mobile">Confirm your email. </span>
            <a className="js-resend-email" href="#" onClick={this.resendMail}>Resend</a>
          </div> : null}

          <div className="DasboardPageMain d-flex flex-grow">

            {/* sidebar with slide-in effect from left on toggle */}

            <SidebarMenu currentLocationPath={currentLocationPath} channels={this.state.channels} />

            <div className="DashboardPage__overlay" />

            <main className="DashboardPage__Content d-flex flex-grow">
              {/* swapping DashboardPage's Child Components based on current url set by <Router/> */}
              <Route path="/dashboard/main" render={() => <Dashboard toggleModal={this.toggleModal} />} />
              <Route path="/dashboard/channels/:id/:channelName" component={VideoStats} />
              <Route path="/dashboard/edit_video" component={EditVideo} />
              <Route path="/dashboard/account" component={Account} />
              <Route path="/dashboard/socialMedia" component={SocialMedia} />
              <Route path="/dashboard/media-library" component={MediaLibrary} />
              <Route path="/dashboard/shares" component={Shares} />
              {/* <Route path="/dashboard/platform/:data"  component={Platforms} /> */}
              {/* <Route exact path="/dashboard/channels/:id/:channelName" component={VideosList} /> */}

            </main>

            {/* Modal With Nested Form to add Chaanel's info. */}
            <Modal className="addChannelModal" isOpen={this.state.modal} toggle={this.toggleModal} >
              <ModalBody>
                <AddChannelForm toggleModal={this.toggleModal} notifySuccess={this.notifySuccess} notifyError={this.notifyError} />
              </ModalBody>
            </Modal>
          </div>
          <Footer />

          {/* React toastify for toast notifications */}
          <ToastContainer
            className={{ textAlign: 'center' }}
            progressClassName={css({ background: '#007aff' })} />
        </div>
      );
    } else {
      return <Redirect to={'/'} />;
    }
  }
}

export default withRouter(DashboardPage);

现在我想访问 &lt;SidebarMenu&gt; 组件内的路由器 url 参数,但在 &lt;SidebarMenu&gt; console.log(this.props.match.params) 内显示的是空对象。

但是如果我在 &lt;Route/&gt; 渲染的任何组件中执行 console.log(this.props.match.params) 例如:

<Route path="/dashboard/account" component={Account} />

我很容易得到 url 中的所有参数。

有没有办法在&lt;SidebarMenu&gt; 中访问所有这些与路由器相关的道具 ?

目前我有条件地在&lt;SidebarMenu&gt; 内渲染 JSX,如下所示:

const currentLocationPath = this.props.currentLocationPath;
const pathArray = window.location.pathname.split('/');

          { pathArray.length > 3 &&
            <Media tag="li" className={`${pathArray.length === 3 ? 'li-active' : null} li-channels align-items-center mb-1 py-1`}>
              {/* Chevron Icon */}
              <Media left middle tag="span" className="media-chevron-right ml-5 mr-1">
                <FontAwesomeIcon size="xs" icon={currentLocationPath == '/dashboard/main' ? faChevronRight : faChevronDown} className="" />
              </Media>

              {/* channel's main body */}
              <Media body className="text-center text-sm-left mb-3 mb-sm-0">
                <Media heading tag="h6" className="m-0">
                  Channels
                </Media>
              </Media>
            </Media> }

【问题讨论】:

  • 您的DashboardPage 是否包含在&lt;Router&gt; 中?
  • 是的。 ReactDOM.render( &lt;Router&gt; &lt;Switch&gt; &lt;Route exact path="/" component={HomePage} /&gt; &lt;Route path="/verify/email/:token" component={HomePage} /&gt; &lt;Route path="/reset/password/:token" component={HomePage} /&gt; &lt;Route path="/dashboard" component={DashboardPage} /&gt; {/* &lt;Route path="/video" component={VideoPage} /&gt; */} &lt;Route component={HomePage} /&gt; &lt;/Switch&gt; &lt;/Router&gt;, document.getElementById('root') ); registerServiceWorker();

标签: javascript reactjs react-router-v4


【解决方案1】:

您没有在&lt;DashboardPage&gt; 渲染中将match 传递给&lt;SidebarMenu&gt;

您可以在 DashboardPage 渲染中将其作为道具传递:

<SidebarMenu match={match} currentLocationPath={currentLocationPath} channels={this.state.channels} />

或者用withRouter包裹它。

【讨论】:

  • 我都试过了,但还是不行。我在&lt;Route /&gt; 组件渲染的组件中获取路由相关的道具,这也是我需要在&lt;Sidebar /&gt; 组件内部访问的内容。
  • 基本上我担心的是,在一个未被&lt;Route /&gt; 组件渲染的组件中,是否有可能访问或传递所有路由道具,例如匹配、历史记录等?
  • 据我所知,withRouter 就是因为这个原因。如果它没有收到道具,我会检查SidebarMenu,为什么它没有收到道具。
【解决方案2】:

尝试在组件中像这样传递props

<Route path="/dashboard/account" render={ (props) => <Account {...props} /> }/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2015-09-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多