【问题标题】:How to get state from one component to other in a different url in REACTJS with hooks?如何使用钩子在 REACTJS 中的不同 url 中从一个组件获取状态?
【发布时间】:2021-10-20 05:15:38
【问题描述】:

例如,主页组件中有一个输入标签和一个提交按钮。在输入标签中,我输入我的姓名并单击提交我的 url 更改为 /info 的路径,在该 url 中我想显示我在输入字段中输入的名称。

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。
  • 您需要将状态提升到最高公共父级并使用反应路由器更改 url,否则您将丢失所有状态。你应该做反应初学者教程。他们涵盖了这一点。 reactjs.org/tutorial/tutorial.html

标签: javascript reactjs react-hooks routeparams


【解决方案1】:

你可以在 react-router-dom 的 useHistory 和 useLocation Hooks 的帮助下做到这一点。只需将您的组件初始化为 BrowserRouter Switch 并在您想要传递状态的组件中导入 useHistory Hook 并在您想要从提交按钮接收更新状态的组件中导入 useLocation。

  <Switch>
    <Route exact path="/form" component={Form} />
    <Route exact path="/data" component={Formdata} />
  </Switch>

将路径和状态推送到 useHistory 的对象中,以从 useHistory 获取数据的方式创建 useLocation 的对象。

import { useState } from "react";
import { useHistory } from "react-router-dom";

const Form = () => {
const [initstate, setInitState] = useState("");
let history = useHistory();
const HandleSubmit = (e) => {
  e.preventDefault();
  history.push("/data", initstate);
};

  return (
    <>
      <form onSubmit={HandleSubmit}>
        <input
          type="text"
          placeholder="text field"
          onChange={(e) => setInitState(e.target.value)}
        />
        <input type="submit" value="Submit" />
      </form>
    </>
  );
};

export default Form;

获取状态数据:

import { useLocation } from "react-router-dom";

const Formdata = () => {
  let location = useLocation();

  console.log(location.state);

  return (
    <>
      <p>{location.state}</p>
    </>
  );
};

export default Formdata;

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2017-10-09
    • 2018-08-05
    • 2021-03-30
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    相关资源
    最近更新 更多