redux-simple-router - perform action based on URL

99封情书 提交于 2020-01-02 07:04:06

问题


I'm using Redux with redux-simple-router.

Here's what I'm trying to do. A user hits a URL like so: http://localhost:3000/#/profile/kSzHKGX Where kSzHKGX is the ID of the profile. This should route to Profile container filled out with the details of the profile with id kSzHKGX.

My routes look like this:

export default (
  <Route path="/" component={App}>
    ...
    <Route path="profile" component={Profile} />
    ...
  </Route>
)

So hitting the above link would give me Warning: [react-router] Location "undefined" did not match any routes

My container looks like this:

@connect(
  state => state.profile,
  dispatch => bindActionCreators(actionCreators, dispatch)
)
export class Profile extends Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    const { getProfileIfNeeded, dispatch } = this.props
    getProfileIfNeeded()
  }
  render() {
    return (
      <section>
      ...
      </section>
    )
  }
}

So normally my container would just be populated from the state as usual in Redux.

Basically I need to have a way of doing some wildcard in the route. Than I need to pass the URL to the action that would pull up the right profile from an API. The question is, is it doable with react-simple-router? Can I do that somehow using UPDATE_PATH? Would it be the proper Redux way? Or should I use something else?


回答1:


Following Josh David Miller's advice, I made my route look like so:

<Route path="admin/profile/:id" component={Profile} />

Than my container got this method to get the profile from API:

componentWillMount() {
  const { getProfile, dispatch } = this.props
  getProfile(this.props.params.id)
}

And this to cleanup (without it I would have the previous profile display for split second on component load - before I hit API in componentWillMount)

componentWillUnmount() {
  this.props.unmountProfile()
}

Update:

As an alternative to the cleanup, I'm considering using the Container Component Pattern. Basically have the outer component do the data fetching and passing the data to the inner component as a prop.



来源:https://stackoverflow.com/questions/34666087/redux-simple-router-perform-action-based-on-url

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