gpt4 book ai didi

reactjs - react 路由器 : share state between Routes without Redux

转载 作者:行者123 更新时间:2023-12-03 13:40:08 25 4
gpt4 key购买 nike

我希望在 2 个兄弟路由之间有一个共享状态(远程获取的客户端列表):TimesheetsClients .
我想尝试一下“纯”React(无 Flux 架构)能走多远。

这个例子有效,但我有一个错误:browser.js:49 Warning: [react-router] You cannot change <Router routes>; it will be ignored所以,它似乎不喜欢异步 Prop 。

constructor(props) {
super(props);
this.state = {
clients : []
}
}

componentDidMount() {
fetch("clients.json")
.then(response => response.json())
.then(clients => this.setState({ clients }));
}

render() {
return (
<Router history={browserHistory}>
<Route path="/" component={Header} >
<Route path="timesheet" component={() => (<Timesheets {...this.state} />) }/>
<Route path="clients" component={() => (<Clients {...this.state} />) }/>
</Route>
</Router>
);
}

是否可以将异步 Prop 发送到每个路由?
或者是否可以在父路由( Header 组件)中设置整个状态,然后从每个子路由( TimesheetsClients 组件)访问此状态?

最佳答案

您可以使用high-order component获取数据并将其注入(inject)到您的顶级组件。然后你可以通过 React.cloneElement 将 props 传递给子路由。

HOC

const FetchHOC = url => Component => class extends React.Component() {
state = { data: null };
componentDidMount() {
fetch(url).then(data => this.setState({ data }));
}
render() {
return <Component {...this.props} {...this.state.data} />;
}
}

路由配置

<Route path="/" component={FetchHOC('http://some-url')(App)}>
<Route path="subroute1" component={SubRoute1} />
<Route path="subroute2" component={SubRoute2} />
</Route>

父路由render()

<div className="App">
{this.props.children && React.cloneElement(this.props.children, {
data: this.props.data,
// ...
})}
</div>

关于reactjs - react 路由器 : share state between Routes without Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108701/

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