Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

reactjs - How send id category in link React?

I have page where I display all categories with this code

{categories.map((category, index) => {
            return(
              <tr key={index}>
                <th scope="row">{index}</th>
                <td>{category.name}</td>
                <td>50</td>
                <td><Link to={{pathname: `/categories/edit/`}}>Edit</Link></td>
                <td><Button variant={'danger'} onClick={deleteCategoryHandler} data-id={category._id}>Delete</Button></td>
              </tr>
            )
          })}

But when I create Component edit Category, and there I Need send with id. which will be better ID and name?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you need to do this:

categories.map((category, index) => {
  const location = {
    pathname: `/categories/edit/`,
    state: {
      category,
    },
  };
  return (
    <tr key={index}>
      <th scope="row">{index}</th>
      <td>{category.name}</td>
      <td>50</td>
      <td>
        <Link
          to={location}
        >
          Edit
        </Link>
      </td>
      <td>
        <Button
          variant={"danger"}
          onClick={deleteCategoryHandler}
          data-id={category._id}
        >
          Delete
        </Button>
      </td>
    </tr>
  );
});

and in the destination component just use something like this to get location object and then its state property:

const location = useLocation();

const category = location?.state?.category;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...