简体   繁体   中英

react is trying to render the page even before the params.id is being fetched so only the if statement is being running every time

I want to render the react code when the id in the params match the id in the data but here react tries to render the code even before props.match.params.id is being executed so only the if statement is being executed can you provide me with a solution to solve this.Ive even tried using useParams() but it does not do anything good.

import data from'./data'
import React  from 'react'



export default function Productdisplay(props) {
 
  const y= props.match.params.id
  const product=data.products.find((x) => x.id===y); //An error lies here

  if(!product){
    return(
      <div>No product to display {}</div>
    )
  }
return(
<>
//Here lies the code I want to render when the ids of the url and data  match 
but as React tries to render the code even before the params is being fetched 
only if statement is being rendered can you give me a solution for this
</>
)
}

What you want to use here is a useEffect that contains your conditions/logic that will run when its depecencies change. Here it is Y . Then store the ouput of your logic from the useEffect into a real state (useState) and not a const. From there you'll be able to trigger the re-render you expect.

import React, { useState, useEffect } from 'react';

function Productdisplay(props) {
  const [products, setProducts] = useState();

  useEffect(() => {
    const y = props ? .match ? .params ? .id;
    const findProducts = data.products.find((x) => x.id === y);

    if (findProducts !== products) {
      setProducts(products);
    }
  }, [data?.products, props?.match?.params?.id]);

  if(!products) return null; 
  return (
    <div>
      // ...
    </div>
  );

I suggest you to read this https://reactjs.org/docs/hooks-effect.html

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