【问题标题】:How do I pass props to non-child component with react router?如何使用反应路由器将道具传递给非子组件?
【发布时间】:2016-09-30 04:25:24
【问题描述】:

我有一个组件不能传统上从父组件继承props。这个组件是通过路由渲染的,不是由父级渲染的,我说的是 <Single /> 组件,它是这个设置中的“细节”组件:

  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={ProfileList} />
      <Route path="/profile/:username" component={Single} /></Route>
  </Router>

ProfileList 组件中提供了道具,并且该组件呈现 Profile 组件,如下所示:

   /* ProfileList render method */
   render() {
      return (
        <div>
          {this.state.profiles.map((profile, i) => 
            <Profile {...this.state} key={i} index={i} data={profile} />)}
        </div>
      );
    }

我正在尝试在ProfileListSingle 组件中重用Profile 组件:

  <Link className="button" to={`/profile/${username}`}>
   {name.first} {name.last}
  </Link>

但在Single 组件中,我无法访问stateprops - 所以我无法呈现此详细信息视图。我知道我可以use redux for passing global state 或在我的Link to="" 中使用查询参数

但是我还不想接触到 redux 并且对查询参数感觉不正确。那么如何在Single 组件中访问this.props.profiles 之类的内容?

【问题讨论】:

  • 也许路由器参数? stackoverflow.com/questions/32901538/…
  • no @Brad - 如果你的意思是这样,我不想查询参数
  • ProfileList 和 Single 是兄弟组件,为什么 Single 不能访问状态?
  • 因为他们是兄弟姐妹而不是父子关系。道具在 ProfileList 中 - 如何将它们传递给 ProfileList 未呈现的单个组件?

标签: reactjs global react-router


【解决方案1】:

redux connect() 完全可以完成这项工作。我认为您应该使用它,因为“很好”您将重新实现 redux 连接,例如

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2015-09-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2018-08-22
    • 2020-07-07
    相关资源
    最近更新 更多