如何在React中从<route>呈现的组件中更改路由?

时间:2017-07-17 07:51:00

标签: reactjs react-router

我在Home内渲染Route组件,以便我可以将状态作为道具传递给组件。

class App extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            page: 'false'
        };
    }
    render() {
        return (
            <Router>
                <div>
                    <Switch>
                        <Route exact path='/' render={()=><Home page={this.state.page}/>} />
                        <Route exact path='/projects' component={Projects} />
                        <Route render={function(){
                            return <p>Not Found</p>
                        }} />
                    </Switch>
                </div>
            </Router>
        )
    }
}

Home组件中,我想从一个函数触发路由更改。因为组件在Route内部呈现,历史道具不会被传入,因此我不能像这样触发路径更改:

class Home extends React.Component{
    constructor(props){
        super(props);
        this.gotoProjects = this.gotoProjects.bind(this);
    }
    gotoProjects() {
        this.props.history.push('/projects');
    }
    render() {
        return (
            <button onClick={this.gotoProjects.bind(this)}>Projects</button>
        )
    }
}

如何在保留组件的路径的同时更改路径?

更新 我使用createBrowserHistory

创建了一个History.js.
import { createBrowserHistory } from 'history'

export default createBrowserHistory()

将App.js更新为

import history from '../history';

class App extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            page: 'false'
        };
    }
    render() {
        return (
            <Router>
                <div>
                    <Switch>
                        <Route exact path='/' render={()=><Home history={history} page={this.state.page}/>} />
                        <Route exact path='/projects' component={Projects} />
                        <Route render={function(){
                            return <p>Not Found</p>
                        }} />
                    </Switch>
                </div>
            </Router>
        )
    }
}

现在,当我点击Home中的按钮时,网址会转到/ projects,但视图仍然会呈现Home而不是Projects。如何在history.push发生后呈现Projects

0 个答案:

没有答案