reactjs - 未捕获的 DOMException:无法在“历史”上执行“pushState”:无法克隆函数(){[本机代码]}
问题描述
我正在 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:无法在“历史”上执行“pushState”:无法克隆函数 () { [本机代码] }。
我尝试了这个解决方案,但它对我不起作用。它仍然给我这个错误或给状态为未定义。我很新的反应,任何帮助将不胜感激
解决方案
正如@Andreas 在评论中提到的那样,当在分配给window.history.state
viahistory.replaceState
或的状态对象中使用 DOM 元素或任何不可序列化的东西时,就会发生此错误history.pushState
。例如 try:history.pushState({node: document.body}, 'title', '#/error')
或使用{node: History}
,它会产生类似的DOMException
错误。要修复它,只需删除有问题的对象,或者以某种方式更慎重地考虑将什么推入状态。