[英]Failed to execute 'pushState' on 'History': function addComment() … could not be cloned
[英]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.replaceState
或history.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.