简体   繁体   English

如何在 react-router-dom v5 中使用 Link 传递和拦截数据

[英]How to pass and intercept data with Link in react-router-dom v5

I am making a simple chat-app.我正在制作一个简单的聊天应用程序。 Users submit a form with name and room, and are sent to the room, with the username.用户提交带有名称和房间的表单,并使用用户名发送到房间。 The problem is, I cannot figure out how to pass the username through via the Link.问题是,我无法弄清楚如何通过链接传递用户名。 This is the relevant code:这是相关代码:

<Link to={{pathname: `/${room}`, state: {the: user} }}> Enter room </Link>

I use simple useState-hooks to set room and username from input.我使用简单的 useState-hooks 从输入中设置房间和用户名。 From what I have read, this way of doing it is deprecated, and I cannot find a proper answer for react-router-dom v5, only 4 and below.根据我的阅读,这种做法已被弃用,我找不到 react-router-dom v5 的正确答案,只有 4 及以下。

Also, I have no idea how I am supposed to intercept this data.另外,我不知道我应该如何拦截这些数据。 This is my App.js code:这是我的 App.js 代码:

return(
        <Router>
            <div className='app' >
                <Switch>
                    <Route exact path='/' >
                        <Menu />
                    </Route>

                    <Route exact path='/:room' >
                        <ChatApp />
                    </Route>
                </Switch>
            </div>
        </Router>
    );

So as you can see, the link sends you to the ChatApp component.如您所见,该链接将您发送到 ChatApp 组件。 To make it as simple as possible, the top of that looks like this:为了使其尽可能简单,顶部看起来像这样:

const ChatApp = (props) => {

but when I console.log(props), all I get is an empty array.但是当我 console.log(props) 时,我得到的只是一个空数组。 Does anyone know a reliable way of passing and intercepting data via Links?有谁知道通过链接传递和拦截数据的可靠方法? Perhaps it should be done a different way?也许应该以不同的方式完成?

Not necessarily the right answer, but the way things look, in rrd@5, you cannot, and you are forced to send the props as params.不一定是正确的答案,但事情的样子,在 rrd@5,你不能,你被迫将道具作为参数发送。 Not sure for objects though虽然不确定对象

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

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