React map function to create <Redirect> which carry wrong parameter

Viewed 206

I am a beginner in React.

A.js

const obj ={
  {name:objA, id:11111},
  {name:objB, id:22222},
};
const [isRedirect, setIsRedirect] = useState(false);


xxxxxxx.....................

return( 

   obj.map((data) => (
      <TableCell onClick = {setIsRedirect(true)}> 
           data.name 
       </TableCell>

   { isRedirect ?  

       
     <Redirect to={{ 
                                         
        pathname:'/user-management', 
                                          
        state:{userID:data.id},
     }}  />   : "" }
   )

 )

user-management.js

 useEffect(() => {
        const history = createHashHistory();
    if (history.location.state && history.location.state.transaction) 
    {
        let state = { ...history.location.state };
        delete state.transaction;
        history.replace({ ...history.location, state });
    }


     console.log(props.location.state.userID); // show 22222


 }

After I click the objA table cell, The code in user-management.js executes, but when I console.log(props.location.state), It shows the user id as 22222 instead of 11111. It seems props.location.state in user-management always stored the last value of json array obj. How can I modify to code? I would be grateful if u guys help. And Sorry for the code structure.

1 Answers

There's probably more going on, but I think the onClick handler should be onClick={() => setIsRedirect(true)}.

I see you are trying to render multiple Redirects, but you've only a single isRedirect state. The entire component renders... every element you map. I suspect when once you toggle the isRedirect true that you probably get a redirect for every element mapped. They all redirect to the same path though, so the last redirect with data is the one you see.

Suggestion

Only render one Redirect conditionally, and set isRedirect to be the data.id value (assumes id's will always be truthy!!!)

...

const [redirectId, setRedirectId] = useState(null);

...

if (redirectId) {
  return (
    <Redirect
      to={{                             
        pathname: '/user-management',      
        state: { userID: redirectId},
      }}
    />
  );
}

return obj.map((data) => (
  <TableCell onClick={() => setRedirectId(data.id)}> 
    {data.name}
  </TableCell>
);
Related