【问题标题】:Changing components based on url with react router使用反应路由器根据 url 更改组件
【发布时间】:2016-10-26 15:56:04
【问题描述】:

这更多是关于反应的架构问题,而不是特定问题,但是对于使用布局组件和几个基于 url 呈现的子组件来管理状态/道具的最佳实践是什么?

注意:我知道有人问过类似的问题,但这有点不同。 [How to update ReactJS component based on URL / path with React-Router

假设我有类似以下代码的内容:一个配置文件页面(主布局视图),其中包含配置文件子部分(设置、首选项、帐户详细信息等)的导航链接,以及一个主面板,其中每个子部分部分被渲染。

所以目前我会有这样的事情: 我的路由器 routes.js

<Router history={browserHistory}>
  <Route path='/profile' component={Profile} >
    <IndexRoute component={Summary} />
    <Route path='/profile/settings' component={Settings} />
    <Route path='/profile/account' component={Account} />
    <Route path='/profile/preferences' component={Preferences} />
  </Route>
</Router>

以及我的配置文件布局组件的精简版 profile.js

class Profile extends React.Component {

  constructor(props) {
    super(props)
  }

  render(){

    let pathName = this.props.location.pathname;

    return(
      <div className='container profile-page'>
        <div className='side-nav'>
          <ul>
            <li><Link to='/profile'>Summary</Link></li>
            <li><Link to='/profile/settings'>Settings</Link></li>
            <li><Link to='/profile/account'>My Account</Link></li>
            <li><Link to='/profile/preferences'>Preferences</Link></li>
          </ul>
        </div>
        <div className='main-content'>
         {this.props.children}
        </div>
      </div>
    )
  }
}

export default Profile;

所以这种工作。子组件将根据 url 呈现。但是那我该如何管理状态和道具呢?我理解 React 和 Flux 的方式是,我希望 Profile 组件管理状态并监听我的商店的更改,并将这些更改传播给它的子组件。它是否正确?

我的问题是似乎没有一种直观的方法可以将 props 传递给 this.props.children 呈现的组件,这让我觉得我当前的架构和/或对通量的理解不正确。

我们将不胜感激。

【问题讨论】:

    标签: javascript reactjs flux


    【解决方案1】:

    我觉得你所做的一切都很好。你走在正确的道路上。

    React 为您提供的 API 组合可以准确处理您不确定如何实现的问题 (way to pass props to components rendered by this.props.children)

    首先,你需要看看cloneElement

    它基本上会采用一个 React 元素,克隆它,然后返回另一个带有 props 的元素,你可以完全根据需要更改、更改或替换。

    此外,将它与 Children Utilities 结合使用 - 循环遍历提供给顶级组件的子元素,并对每个元素分别进行必要的更改。

    建议的示例用法可以很简单

    <div className='main-content'>
        {React.children.map(this.props.children, (child, index) => {
           //Get props of child
           const childProps = child.props;
    
           //do whatever else you need, create some new props, change existing ones
           //store them in variables
    
           return React.cloneElement(child, {
               ...childProps, //these are the old props if you don't want them changed
               ...someNewProps,
               someOldPropOverwritten, //overwrite some old the old props 
           });
         )}
    </div>
    

    使用这些工具在任何地方创建真正通用且可重复使用的组件。 Children 中更常用的实用程序是 mapforEachtoArray。每个人都有自己的目标。

    希望这会有所帮助。

    【讨论】:

    • 好的,现在这更有意义了。非常感谢您的全面回答。
    • 非常欢迎,这就是董事会的宗旨。希望它也能帮助其他人。感谢一个好问题,这些天几乎没有。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2020-05-21
    • 2021-01-02
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多