gpt4 book ai didi

javascript - 使用 react 路由器更改基于 url 的组件

转载 作者:搜寻专家 更新时间:2023-11-01 04:30:01 25 4
gpt4 key购买 nike

这更多是关于 React 的架构问题,而不是具体问题,但是什么是使用布局组件和基于 url 呈现的多个子组件管理状态/ Prop 的最佳实践?

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

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

所以目前我会有这样的事情:我的路由器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 呈现。但是我该如何管理状态和 Prop 呢?按照我对 React 和 Flux 的理解,我希望 Profile 组件管理状态并监听我的商店的变化,并将这些变化传播给它的子组件。这样对吗?

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

一些指导将不胜感激。

最佳答案

我觉得你做的很好。您走在正确的道路上。

React 为您提供的 API 组合将准确处理您不确定如何实现的内容(将 props 传递给由 this.props.children 呈现的组件的方式 )

首先,你需要看一下cloneElement

它基本上会获取一个 React 元素,克隆它,然后返回另一个带有 Prop 的元素,您可以完全根据您的需要更改、改变或替换这些元素。

此外,将它与 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。每个人都有自己的目标。

希望这对您有所帮助。

关于javascript - 使用 react 路由器更改基于 url 的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com