![](/img/trans.png)
[英]Why do I need to refresh the page when using Link and Switch with react-router-dom?
[英]Why `Failed to execute 'pushState' on 'History'` when using `Link` from react-router-dom?
我看過類似的帖子,但找不到答案,就我而言,我正在嘗試從<App />
傳遞一個操作:
addExpense = (expense) => {
console.log('Hello From AddExpenseForm');
}
到我正在渲染<AddExpenseForm />
組件的/create
route
<Link to={{
pathname: '/create',
state: { addExpense: this.addExpense }
}}> Create Expense</Link>
該鏈接已呈現,但當我單擊它時,在控制台中出現錯誤:
Uncaught DOMException: Failed to execute 'pushState' on 'History': function (expense) {
console.log('Hello From addExpense');
} could not be cloned
為什么會這樣,這里的解決方法是什么?
Index.js 中的路由:
const Routes = () => {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={App} />
<Route path="/create" exact component={AddExpenseForm}/>
<Route path="/expense/:expenseId" name="routename" component={ExpenseDetails} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)
}
應用程序.js:
addExpense = (expense = {}) => {
console.log('Hello From AddExpenseForm');
}
goToNextPage = (addExpense) => {
this.props.history.push({
pathname: '/create',
state: { addExpense: this.addExpense }
});
}
render() {
return (
<div>
<Header
/>
<button onClick={this.goToNextPage}>Create</button>
...
首先,為您的addExpense
函數添加一些默認值:
addExpense = (expense = DEFAULT) => {
console.log('Hello From addExpense');
}
然后使用Link
:
<Link to={`/ideas/${this.addExpense}`}>Create Expense</Link>
或試試這個(更好的方法):
goToNextPage = (addExpense) => {
this.props.history.push({
pathname: '/create',
state: { addExpense: addExpense }
});
}
在 next ( create
) 組件中使用傳遞的值,如下所示:
this.props.location.state.addExpense();
您正在使用BrowserRouter
,它使用 HTML5 歷史 API( window.history
),與Router
和HashRouter
不同。
BrowserRouter 的history.push
方法到 HTML5 歷史的映射如下:
this.props.history.push({
pathname: '/create',
state: { addExpense: this.addExpense }
});
pathname('/create')
> window.history.push('create')
state({ addExpense: this.addExpense })
> window.history.pushState({ addExpense: this.addExpense })
實際問題在於window.history.pushState
因為它將狀態存儲為string
並且大小限制為640k 個字符。
來源: https : //developer.mozilla.org/en-US/docs/Web/API/History/pushState
就我而言,我使用BrowserRouter
並發現我要么需要運行本地服務器,要么切換到HashRouter
因為BrowserRouter
安全原因, BrowserRouter
無法使用file://
路徑。
https://github.com/ReactTraining/react-router/issues/6533#issuecomment-451969973
我遇到了同樣的問題,但是當我將所有反斜杠更改為如下所示的正斜杠時,錯誤得到解決:-
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/About">About</NavLink></li>
<li><NavLink to="/Contact">Contact</NavLink></li>
就我而言,這是由於嘗試路由到帶有兩個"/"
字符的路徑引起的。 我是這樣寫的:
history.push(`${location.pathname}/somePath`);
...但如果location.pathname
是"/"
會嘗試轉到"//somePath"
,從而導致錯誤,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.