【问题标题】:How do I redirect to another page and also transfer value to the page in React?如何重定向到另一个页面并将值转移到 React 中的页面?
【发布时间】:2021-08-16 01:33:36
【问题描述】:

这是我的按钮

<Button onClick={this.clickMe.bind(this, data)} className="ViewDetailsBtnLink">View Details</Button>

这就是clickMe函数

clickMe(data){
    console.log(data);    
}

现在,它所做的只是在控制台中显示数据。我希望将数据传输到另一个页面并重定向到显示数据的 ViewDetails 页面。 任何帮助表示赞赏。

【问题讨论】:

  • 你可以使用 react 路由器的历史,去检查这个 HOC reactrouter.com/web/api/withRouter 然后尝试使用历史道具推送到你想要的路由,并将其作为路由器状态的一部分.

标签: reactjs react-native rxjs react-router react-hooks


【解决方案1】:

您可以使用React Router 库来路由您的页面。例如,首先为您的页面创建路由器,如下所示:

在你的根文件中,或者创建另一个名为“Router.js”的文件并渲染它,然后你可以在你的根文件中渲染&lt;Router/&gt;组件。

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useHistory
} from "react-router-dom";

const BasicExample = () => {
  return (
    <Router>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
        </Switch>
    </Router>
  );
}

export default BasicExample;

在您要导航的文件中,例如 Home.js :

const Home = () => {
  const history = useHistory();
  
  const clickMe = (data) => {
    history.push("/about", {data: data});  
  }
  return (
    <div>
      <h2>Home</h2>
      <button onClick={() => clickMe({name: "test"})} className="ViewDetailsBtnLink">View Details</button>
    </div>
  );
}

export default Home;

在您要访问传递参数的文件中。这是关于.js:

const About = () => {
  const history = useHistory();
  const data = history.location.state.data;
  
  return (
    <div>
      <h2>About</h2>
      <p>{JSON.stringify(data)}</p>
    </div>
  );
}

export default About;

如您所见,您可以使用useHistory 挂钩导航到带有参数的另一个页面并访问从上一页传递的参数。

【讨论】:

  • 这也是我的想法。这种方法对我来说似乎很干净。
  • 请注意,useHistory()react-router-dom v6 中被 useNavigate() 取代。见stackoverflow.com/a/66971821/1842332
【解决方案2】:

2 种方法。

useContext 和

使用参数

使用上下文:

拥有一个全局上下文,其中包含一些您可以在每个页面上使用的信息。

https://reactjs.org/docs/context.html

使用参数:

转到类似“hello/randombitsofinformation”的页面

作为“hello/:slug”放在路由器中

那么你就让 slug = useParams();

<h1>{slug}</h1> 

将与

相同
<h1>randombitsofinformation</h1>

【讨论】:

  • 哦,好吧。但问题是我的代码在 React Class 组件中。如何在 React 类组件中使用 useParams?
猜你喜欢
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多