React router v4 - Rendering two components on same route

五迷三道 提交于 2019-12-10 18:56:59

问题


I have these routes

 <Route exact path={`/admin/caters/:id`} component={Cater} />
 <Route exact path={'/admin/caters/create'} component={CreateCater} />

When I navigate to the first route I get a cater with a given ID. And the Cater component is rendered

When I navigate to the second route, the CreateCater component is rendered on the page, but I noticed that some redux actions that are used in the Cater component are being run. So both component are somehow being rendered - but I can't figure out why.

Here are the components:

Cater:

class Cater extends Component {

  async componentDidMount() {
        console.log('Cater component did mount')
        const { match: { params: { id }}} = this.props
        this.props.get(id)
    }

    render() {
        const { cater } = this.props
        if(!cater) {
            return null
        }
        else {
            return (
                <div>
                   ... component data ...
                </div>
            )
        }
    }
}

const mapStateToProps = (state, props) => {
    const { match: { params: { id }}} = props
    return {
        cater: caterSelectors.get(state, id)
    }
}

const mapDispatchToProps = (dispatch, props) => {
    return {
        get: (id) => dispatch(caterActions.get(id))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cater)

CreateCater:

export default class CreateCaterPage extends Component {
    render() {
        return (
            <React.Fragment>
                <Breadcrumbs />
                <CaterForm />
            </React.Fragment>
        )
    }
}

When I go to /admin/caters/create' I can see the console.log in the componenDidMount() lifecycle method inside the Cater component.

I cant figure out what I am doing wrong :(


回答1:


/create matches /:id, so it makes sense that this route matches. I recommend forcing :id to look for numeric only:

<Route exact path={`/admin/caters/:id(\\d+)`} component={Cater} />
<Route exact path={'/admin/caters/create'} component={CreateCater} />

Likewise, you can follow @jabsatz's recommendation, use a switch, and have it match the first route that matches. In this case, you would need to ensure that the /admin/caters/create route is the first <Route /> element matched.




回答2:


The problem is that :id is matching with create (so, it thinks "see cater with id create"). The way to solve this is to put the wildcard matching route last, and wrapping all the <Routes/> with a <Switch/>, so it only renders the first hit.

Check out the docs if you have any more questions: https://reacttraining.com/react-router/core/api/Switch



来源:https://stackoverflow.com/questions/53213614/react-router-v4-rendering-two-components-on-same-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!