简体   繁体   English

React Router Dom,使用 useNavigate 将数据传递给组件

[英]React Router Dom, pass data to a component with useNavigate

I'm using useNavigate to go to the component and need to pass data (a state) to this this ChatRoom component when I click a button.我正在使用useNavigate转到组件,并且在单击按钮时需要将数据(状态)传递给此ChatRoom组件。 This component is on the route /chatroom .该组件位于/chatroom路线上。 I'm using React Router Dom v6 .我正在使用 React Router Dom v6 I have read the documentation but I cannot find what I'm looking for.我已阅读文档,但找不到所需的内容。

export default function Home() {
  const [username, setUsername] = useState("");
  const [room, setRoom] = useState("");

  const navigate = useNavigate();

  const handleClick = () => {
    navigate("/chatroom");
  };

  return (<button
            type="submit"
            className="btn"
            onClick={() => {
              handleClick();
            }}
          >
            Join Chat
          </button>
)}

1. Solution 1.解决方案

You can pass data to the component that corresponds to /chatroom in React Router Dom v6 like this:您可以将数据传递给与 React Router Dom v6中的/chatroom对应的组件,如下所示:

navigate('/chatroom', { state: "Hello World!" });

And consume it with the help of useLocation hook this way:并以这种方式在useLocation钩子的帮助下使用它:

import { useLocation } from "react-router-dom";
function ChatRoom() {
  const { state } = useLocation();
  return (
    <div>
      {state}
    </div>
  );
}
export default Chatroom;

If you wanna pass multiple state, use an object, like so:如果您想传递多个状态,请使用一个对象,如下所示:

navigate('/chatroom', { state: {id:1, text: "Hello World!"} });

2. Troubleshot 2. 故障排除

As you can try it here on this CodeSandbox , it works only if the passed data is called state .正如您可以在此CodeSandbox上尝试的那样,它仅在传递的数据称为state时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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