![](/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.