简体   繁体   中英

How to use useParams inside a useEffect?

I want to use useParams inside of useEffect but I am getting error saying that "Uncaught TypeError: Cannot read properties of undefined (reading 'params')".

app.js

<Route>
  <Route path="/product/:id" element={<ProductDetails />} />
</Route>

ProductDetails.js

const dispatch = useDispatch();
const { id } = useParams();

  useEffect(() => {
    dispatch(getProductDetails(match.params.id));
  }, [dispatch, match.params.id]);`

It is giving me error as I have mentioned above.

It looks like you half converted some code/logic from react-router@5 where there was a match prop injected into the component to react-router@6 where you instead use the useParams hook. match is simply undefined so an error is thrown when attempting to access into it a params property.

The useParams hook replaces entirely props.match.params . The id route path parameter alone is the dependency now.

const dispatch = useDispatch();
const { id } = useParams();

useEffect(() => {
  dispatch(getProductDetails(id));
}, [dispatch, id]);

I don't think you want to use a hook inside of a useEffect function. To answer your question

You could try this

useEffect(() => {
    dispatch(getProductDetails(match?.params?.id));
  }, [dispatch, match?.params?.id]);`

But you're using javascript not typescript, so you can try this.

const param = match && match.params ? match.params.id : ''

useEffect(() => {
  if (param) {
    dispatch(getProductDetails(param));
  }
}, [dispatch, param]);

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