重定向到新选项卡时通过链接传递状态

Abh*_*hiz 10 reactjs react-router

情况 1: 重定向到同一选项卡中的新路由。

<Link to={{ pathname: "/modify_items", state: { foo: "bar" } }} >
Run Code Online (Sandbox Code Playgroud)

当我输入console.log(this.props.location.state);状态时{ foo: "bar" },会打印出来。

情况2: 重定向到新选项卡中的新路线。

<Link to={{ pathname: "/modify_items", state: { foo: "bar" } }} target="_blank" >
Run Code Online (Sandbox Code Playgroud)

当我输入时,console.log(this.props.location.state);状态变为undefined.

My goal is to pass data to a new tab. Please guide me if there is any other way to achieve this in React.js. I just want to pass data to a new tab.

Rao*_*oul 5

我认为这对于链接状态来说是不可能的。因为如果你离开这个页面,你的记忆就会被清除。如果您想在不同选项卡上共享状态,您可能需要使用查询或路径参数。

对于路径参数: 在react-router v4中获取路径参数

对于查询变量:设置链接如下:

<Link to={{ pathname: '/foo', query: { foo: "bar" } }}/>

并使用可能的库来获取查询参数。例如https://www.npmjs.com/package/query-string。


Sel*_*çuk 3

Since the _blank opens a new tab so it is another instance of your app even the app is the same app the internals are different. But you can use something like localStorage.

\n

Since they will be persisted and will be shared for same origin you will have access to it in the new or any tab or window of your application. You need to query it in the component mount or after first render with and useEffect hook with a second parameter being probably empty array, []. For hooks checkout React docs if you use them.

\n

Another way is to use the querystring. You can receive the query string from your opened comopenent instance.

\n

I am sure you can use any other persistense mechanism, like Indexed DB, Cookies, etc.

\n

There are a few other ways coming into my mind under the umbrella web messaging; Broadcast Channel API, Window.postMessage, and Channel Messaging API that you may make use of.

\n

If you state is relatively small it mifght be good to use querystring, or localStorage is the easiest way to go. If your data way more bigger you can use Indexed DB. It is async. Only be careful when it completes write, then you get it in your new window, tab.

\n

在持久性使用案例中,在导航之前写入持久性,如果在导航之前是异步的,只需等待写入过程(通过在特定用例中打开新选项卡/窗口)。

\n

人们可以通过右键单击并从上下文菜单中进行选择来导航到新选项卡。\xc4\xb1n 这种情况页面可见性 API can be used on the right clicked page in a React effect (attaching its effects in an React effect with an empty second argument to React effect) and the data can be written again to a persistence mechanism, one of above mentioned ones, and the rest I mean the operations in the opening tab will be the same.

\n

由于写入机制可能会延迟,即使它是同步的,如果不是以编程方式打开新选项卡,也可能会在写入完成之前发生。在这种情况下,打开选项卡的 React 效果读取写入的数据可能会过早读取。为了规避这些解决方法,例如通过 a 等待setTimeout读取,可以简单地使用,但是,一种以编程方式正确且保证定时的方法是使用我上面提到的适当的 Web 消息传递 API 之一,例如Broadcast Channel、postMessage和Channel Messaging API。

\n