【问题标题】:How to access state passed through Link element when opening in a new tab?在新选项卡中打开时如何访问通过链接元素传递的状态?
【发布时间】:2021-10-20 11:17:42
【问题描述】:

我正在将一个状态从 Link 元素传递到另一个组件,如果我单击它可以正常工作,但是如果我尝试在新选项卡中打开链接,则状态不会被传递。我该如何解决这个问题?

参考代码:

<Link to={{pathname:"/open-page", state:{key: 'hello'}}}/>

openPage.js


import React, { useEffect, useRef } from 'react';
import { bool } from 'prop-types';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { createWidget } from '@typeform/embed';
import { injectIntl, intlShape } from '../../util/reactIntl';


export const OpenPageComponent = props => {
  const { intl, scrollingDisabled } = props;

  console.log('state', props.location.state.key);  //undefined on opening in a new tab

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    我认为这是因为您通过窗口对象而不是 react-router 进行重定向,链接的核心是 url 重定向,您需要在 react-router 中使用 history.push 来保持状态并使用它在新窗口中?希望这会有所帮助:

    https://reactrouter.com/web/api/history

    this.props.history.push('/');
    
    const LoginButton = ({ history }) => (
      <button onClick={() => { history.push('/login'); }} >
        Log in
      </button>
    );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2013-07-16
      • 2021-04-14
      相关资源
      最近更新 更多