即使使用WithRoute

时间:2018-11-01 00:05:08

标签: reactjs react-router

我有一个足够简单的react应用。我有两个重定向的按钮/动作。 sign outadd。退出有效,但添加无效。

add点击之前

history.location'/' location'/'

add单击之后

history.location'/添加' location'/添加'

但相关组件无法渲染。

router.js

let appHistory = createHistory();

const appRouter = () => (
    <Router history={appHistory}>
        <Switch>
            <Route path="/signin" component={SignInUp} exact={true} />
            <Route path="/" component={Landing} />
            <Route path="/add" component={CreateEvent} />
            <Route path="/eventview" component={EventDetails} />
        </Switch>
    </Router>
)

主要组件

import React, {Component} from 'react';
import RequireAuth from './RequireAuth';
import {startSignOut} from '../actions/auth';
import {fetchEvents} from '../actions/event';
import {connect} from 'react-redux';
import {withRouter} from 'react-router';
import EventItem from './EventItem';
import Header from './Header';

const EventDisplay = class EventDisplay extends Component {

    componentDidMount = () => {
        this.props.fetchEvents();
    }

    handleAddEvent = () => {
        console.log(this.props);
        this.props.history.push('/add');
    }

    handleSignOut = () => {
        this.props.startSignOut();
    }

    render() {
        return (
            <div>
                <Header signOut={this.handleSignOut}/>

                {
                    this.props.events.map((event, ind) => {
                        return <EventItem key={ind} history={this.props.history} index={ind + 1} event={event}/>
                    })
                }
                <button onClick={() => this.handleAddEvent()}>+</button>
            </div>
        )
    }
}

const mapDispatchToProps = (dispatch) => ({
    startSignOut: () => startSignOut(dispatch),
    fetchEvents: (userId) => dispatch(fetchEvents(userId))
});

const mapStateToProps = (state) => ({
    events: state.events
})

const connectedWithRouter = withRouter(connect(mapStateToProps, mapDispatchToProps)(RequireAuth(EventDisplay)));

export default connectedWithRouter;

Header.js

const Header = (props) => {
    return (
        <div>
            <h2>Eventio</h2>
            <span>circle</span>
            <span>user</span>
            <button onClick={() => props.signOut()}>Sign out</button>
        </div>
    )
}

export default Header;

1 个答案:

答案 0 :(得分:1)

您的Route和路径/将用于非/signin的任何路径。给它一个exact道具,它将仅用于路径/

const appRouter = () => (
    <Router history={appHistory}>
        <Switch>
            <Route exact path="/" component={Landing} />
            <Route path="/signin" component={SignInUp} />
            <Route path="/add" component={CreateEvent} />
            <Route path="/eventview" component={EventDetails} />
        </Switch>
    </Router>
)