reactjs - React 路由 - 如何在父组件中使用 OnClick 组织重定向
问题描述
我真的很困惑在我的代码中放置路由器、路由和重定向/history.push 的位置。在我的子组件中单击按钮时,将onIndexChange()
调用父组件的方法。(因为我需要使用一些以前构建的组件,所以我不能使用Link
)。我希望该onIndexChange(newIndex)
方法根据新的索引值重定向用户。我在父组件的方法中定义了我的Router
和。我不明白如何或在何处插入组件/调用 history.push 以便调用正确的。我需要修改什么?Routes
render
Redirect
Route
应用程序.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
activeIndex: 0,
};
this.onIndexChange = this.onIndexChange.bind(this);
}
onIndexChange(newIndex) {
const profileType = this.state.profileType.toLowerCase();
const routePath = `${profileType}/${newIndex}`;
this.setState({activeIndex: newIndex});
//this.context.router.push(routePath); ??
//return <Redirect push to={routePath} />; ??
}
render() {
return (
<div className="ui container">
<MemoryRouter>
<div>
<Header onIndexChange={this.onIndexChange} />
<Route exact path="/standard/0" render = { (props) => <StandardOverview {...props} {..overviewProps}/> } />
<Route exact path="/standard/1" render = { (props) => <StandardActivity {...props}{...activityProps} /> } />
<Route exact path="/special/0" render = { (props) => <SpecialOverview {...props}{...overviewProps} /> } />
<Route exact path="/special/1" render = { (props) => <SpecialInfo {...props} /> } />
</MemoryRouter>
</div>
</MemoryRouter>
</div>
);
};
Header.js(子)
render() {
return <SpecialNavigation tabs={tabs} onClick={this.props.onIndexChange} />;
}
解决方案
也许您可以使用由提供的历史apireact-router
并利用来为您的组件以及需要访问历史 api 的任何其他组件withRouter
创建高阶组件。App
然后将允许这些高阶组件推送到浏览器的历史记录。
直接来自文档:
“您可以通过 withRouter 高阶组件访问历史对象的属性和最接近的匹配项。 withRouter 将在渲染时将更新的匹配、位置和历史道具传递给包装的组件”
类似于:(对于App.js
)
import React from "react";
import { withRouter } from "react-router-dom";
class App extends Component {
...
onIndexChange(newIndex) {
const profileType = this.state.profileType.toLowerCase();
const routePath = `${profileType}/${newIndex}`;
this.setState({activeIndex: newIndex});
// assuming your newIndex correctly contains the new route
this.props.history.push(newIndex);`
}
...
};
export default withRouter(App);
注意:您可以将此技术应用于需要访问历史 API 的任何组件。
希望这会有所帮助!
推荐阅读
- reactjs - Error shallow Jest Enzyme React cannot find "store"
- straight-line-detection - 如何找到通过最多点的直线?
- node.js - 尝试使用 nodeJS 调用 MongoDB 时未定义获取错误“DB”
- math - 优化函数(例如,电容器充电)曲线的参数以拟合数据
- javascript - iOS Safari Web Audio API 限制问题
- php - API 为不同的参数返回 500 'Internal Server Error'
- c# - .NET Core 子域地址与区域
- java - 如何使用 R2dbc 从 Postgresql 中提取 jsonb 到 Spring webflux
- android - 当我克隆我的 github 项目时,我的项目不工作
- c - C 中 printf 语句中的 %# 标志是什么?