首页 > 解决方案 > React 路由 - 如何在父组件中使用 OnClick 组织重定向

问题描述

我真的很困惑在我的代码中放置路由器、路由和重定向/history.push 的位置。在我的子组件中单击按钮时,将onIndexChange()调用父组件的方法。(因为我需要使用一些以前构建的组件,所以我不能使用Link)。我希望该onIndexChange(newIndex)方法根据新的索引值重定向用户。我在父组件的方法中定义了我的Router和。我不明白如何或在何处插入组件/调用 history.push 以便调用正确的。我需要修改什么?RoutesrenderRedirectRoute

应用程序.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} />; 
}

标签: reactjsreact-router-dom

解决方案


也许您可以使用由提供的历史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 的任何组件。

希望这会有所帮助!


推荐阅读