如何将状态从一个反应路线传递到另一个反应路线? [英] How can i pass a state from one react route to another react route?

查看:56
本文介绍了如何将状态从一个反应路线传递到另一个反应路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个具有多条路线的应用程序,因此您可以猜到我需要在不同的路线之间传输数据,我正在使用 react-router-dom 使用 在这些路线之间导航/重定向>useHistory.push("/route") 有什么方法可以让我的一条路线中的状态被另一条路线访问,因为它们位于不同的模块中,如下所示

I am building an app with multiple routes so as you can guess i need to transfer data between different routes, I am using react-router-dom to navigate/redirect between those routes using useHistory.push("/route") is there any way that the states in one of my route could be accessed by my another route as they are located in different modules as shown below

<Switch>
            <Route exact path = "/">
                <Home/>
            </Route>
            <Route exact path = "/login">
                <Login/>
            </Route>    
            <Route exact path = "/signup">
                <Signup/>
            </Route>
        </Switch>
    </Router>

那么谁能告诉我如何将一些状态从/login 发送到/home 等任何帮助表示赞赏..

so can anyone tell me how can I send some states from /login to /home etc any help is appreciated..

推荐答案

这是一个有趣的问题,有很多方法.

This is an interesting question, there're ways.

import { useHistory } from 'react-router-dom'
 
const Component = () => {
  const history = useHistory()
  ...
  history.push('/bulletin', { type: 'success' });
}

这个type会出现在那个路由下

This type will show up under that route

import { useLocation } from 'react-router-dom'

const Component = () => {
  const location = useLocation()
  const { type } = location.state

本地存储

将其保存在浏览器内本地存储中的某个位置,然后在下一个路由中提取.

Local storage

Save it somewhere in local storage inside browser and then next route pick it up.

调用一个 api 来保存该信息,因此下一个路由将通过另一个 api 调用来获取它.

Call an api to save that info, so next route will pick it up via another api call.

以上都是解耦方式,应该是可扩展的.有时您可以将两条路由物理连接在一起,例如.只需在第一个组件中再次重用第二个组件即可.

All above are decoupled way which should be scalable. Sometimes you can wire two routes physically together, ex. just reuse it again the second component in first component.

这篇关于如何将状态从一个反应路线传递到另一个反应路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆