Route Status Name in React + Redux

I have 2 routes using the same component (form), one for creating a new entry, and the other for editing. The state name has been removed from the React Router, I can’t just check if this.route.name === 'edit' => fetch (itemAPI).

One option is to write a reducer / action to create an “edit” state in my redux store, but I was wondering if this is the best practice, and if there is an easier way to check where I am in the application (which route),

My routes:

<Route component={ItemNew} path='/items/edit/:id' />
<Route component={ItemNew} path='/items/new' />

In my ItemNew component, I would like to:

componentDidMount () {
    let stateName = this.props.location.state
    if(stateName === 'edit') {
        this.props.fetchItem() // dispatch API action
    }
}
+4
source share
1

Route, URL-, this.props.route; Route, , this.props.routes. Route . :

<Route component={ItemNew} name="edit" path='/items/edit/:id' />
<Route component={ItemNew} name="add" path='/items/new' />

componentDidMount () {
  if(this.props.route.name === 'edit') {
    this.props.fetchItem() //dispatch API action
  }
}
+2

Source: https://habr.com/ru/post/1622551/


All Articles