我正在 visual studio 2017 提供的 reactjs 模板中创建一个小型 Web 应用程序。我陷入了这样一种情况,我希望将函数作为状态传递给子组件,然后通过子组件调用该函数。我有一个 header 组件,其中有一个名为 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 组件,然后从那里调用该函数。
此代码不会给我任何编译时错误,但每当我单击登录链接时,它都会给我以下错误
Uncaught DOMException: Failed to execute 'pushState' on 'History': function () { [native code] } could not be cloned.
我试过了 this解决方案,但它对我不起作用。它仍然给我这个错误或给出未定义的状态。我对 react 很陌生,我们将不胜感激
最佳答案
当 React 组件状态包含非序列化对象时,我遇到了同样的问题。
我只需要将整个 React 状态对象字符串化,然后将其推送到浏览器的历史状态,如下所示:
window.history.pushState(JSON.stringify(state), "", getSecuredURL(url));
关于reactjs - 未捕获的 DOMException : Failed to execute 'pushState' on 'History' : function () { [native code] } could not be cloned,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50618225/