简体   繁体   中英

react redux change query params with components

I have an isomorphic react application using redux,react-router, react-router-redux, I want to bind my components with url query params and when the query params changed, send request to an API and update my state and finally fetch data. I know with react-router-redux it automatically update my state. Also I want to show a pre-loader (spinner) to user when data is fetching. what is the best way to write an action creator for this issue ? thanks

I want to show a pre-loader (spinner) to user when data is fetching

Pass a data prop to your component. When it's undefined , show a spinner.

const MyComponent = (props) => {
  if (!props.data) return <Spinner />
  ...
}

When the query params changed, send request to an API and update my state and finally fetch data

The most simple solution (this can get quite complex depending on your needs) is to fire this logic on the Component's lifecycle hooks.

When the route changes react-router, with a typical configuration, will cause the component to render if you were previously on a different route, and update if you were previously on the same route (ie the same path, but with different query params).

So for the first case, use componentDidMount , for the second case, use comonentDidUpdate(prevProps, prevState) lifecycle hook.

To map the asynchronous API call to redux action(s), use a library like redux-thunk or probably more tailored to this use case, redux-promise-middleware . How to use those is a bit deep in scope for me to go into here, but they both have excellent documentation.

In the end, you'll want to map those actions in a reducer put the response data somewhere in your state tree, then using react-redux bind that location in the state tree to the data prop on your Component, as I mentioned before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM