繁体   English   中英

未捕获的 DOMException:无法在“历史”上执行“pushState”:函数 () { [本机代码] } 无法克隆

[英]Uncaught DOMException: Failed to execute 'pushState' on 'History': function () { [native code] } could not be cloned

我正在 Visual Studio 2017 提供的 reactjs 模板中创建一个小型 Web 应用程序。我遇到了一种情况,我希望将函数作为状态传递给子组件,然后通过子组件调用该函数。 我有一个标题组件,其中有一个名为setLogInTrue()的方法,我想将其传递给我的 SignIn 组件。 以下是我的代码:-

头文件.tsx

class HeaderState {
isLoggedIn: boolean;
}

export class Header extends React.Component<HeaderProps, HeaderState> {
constructor() {
    super()
    this.state = ({ isLoggedIn: false });
    this.setLogInTrue= this.setLogInTrue.bind(this);
}

setLogInTrue() {
    this.setState({ isLoggedIn: true });
}

public render(){
//Some elements
<NavLink className="link header_row_link" to={{ pathname: '/signIn', state: this.setLogInTrue }}> //<-- i thought this would work and give the function in the location of SignIn components state but it does not.
              Sign In
</NavLink>
  }
}

登录.tsx

export class SignIn extends React.Component<RouteComponentProps<{}>, {}>  {

constructor() {
    super();
}

public render() {
    return <div className="signin_wrapper">
        <SignInContent />
    </div>;
  }
}

我想在此处访问该函数并将其传递给 SignInContent 组件,然后从那里调用该函数。

这段代码没有给我任何编译时错误,但是每当我点击登录链接时,它都会给我以下错误

未捕获的 DOMException:无法在“History”上执行“pushState”:无法克隆 function () { [native code] }。

我试过这个解决方案,但它对我不起作用。 它仍然给我这个错误或给出未定义的状态。 我对反应很陌生,任何帮助将不胜感激

当 React 组件状态包含非序列化对象时,我遇到了同样的问题。

我只需要在将整个 React 状态对象推送到浏览器的历史状态之前将其字符串化,如下所示:

window.history.pushState(JSON.stringify(state), "", getSecuredURL(url));

正如@Andreas 在评论中提到的那样,当在通过history.replaceStatehistory.pushState分配给window.history.state的状态对象中使用 DOM 元素或任何不可序列化的内容时,就会发生此错误。 例如尝试: history.pushState({node: document.body}, 'title', '#/error')或使用{node: History}代替,它会产生类似的DOMException错误。 要修复它,只需删除有问题的对象,或者以某种方式更加慎重考虑将什么推入状态。

我在推送包含函数的 React 组件状态时也遇到了同样的问题。 我不想调用JSON.strinfigy因为它可以包含日期并且那些不能很好地字符串化/解析。 相反,我选择这样做:

window.history.pushState(cleanStateForHistory(state), "", someURL);

/**
 * Remove the functions from the state. They can't been pushed into the history.
 */
export function cleanStateForHistory(state) {
  const stateWithNoFunctions = {};
  for (const key of Object.keys(state)) {
    if (typeof key !== "function") {
      stateWithNoFunctions[key] = state[key];
    }
  }
  return stateWithNoFunctions;
}

暂无
暂无

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

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