javascript 使用 react-router-dom 中的“Link”时,为什么“无法在“历史”上执行“pushState”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46800237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:55:42  来源:igfitidea点击:

Why `Failed to execute 'pushState' on 'History'` when using `Link` from react-router-dom?

javascriptreactjsreact-router

提问by karolis2017

I've seen similar posts but couldn't find an answer and in my case, I'm trying to pass an action from <App />:

我看过类似的帖子,但找不到答案,就我而言,我正在尝试从<App />以下位置传递操作:

  addExpense = (expense) => {
    console.log('Hello From AddExpenseForm');
  }

to /createroute where I'm rendering <AddExpenseForm />component

/create路线在那里我渲染<AddExpenseForm />组件

<Link to={{
  pathname: '/create',
  state: { addExpense: this.addExpense }
}}> Create Expense</Link>

The link is rendered but when I click on it I get an error in console:

该链接已呈现,但当我单击它时,在控制台中出现错误:

Uncaught DOMException: Failed to execute 'pushState' on 'History': function (expense) {
      console.log('Hello From addExpense');
    } could not be cloned

Why is that and what's the workaround here?

为什么会这样,这里的解决方法是什么?

My updated code:

我更新的代码:

Routes in Index.js:

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>
  )
}

App.js:

应用程序.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>
        ...

采纳答案by BlackBeard

Firstly, add some default value to your addExpensefunction:

首先,为您的addExpense函数添加一些默认值:

  addExpense = (expense = DEFAULT) => {
    console.log('Hello From addExpense');
  }

ThenUse Link:

然后使用Link

<Link to={`/ideas/${this.addExpense}`}>Create Expense?</Link>         

ORTry this (Better Approach):

试试这个(更好的方法):

  goToNextPage = (addExpense) => {
    this.props.history.push({
      pathname: '/create',
      state: { addExpense: addExpense }
    });
  }

In next (create) component use the passed on values like this:

在 next ( create) 组件中使用传递的值,如下所示:

this.props.location.state.addExpense();

回答by datchung

In my case, I was using BrowserRouterand found out that I either needed to run a local server or switch to HashRoutersince BrowserRouterdoes not work with a file://path due to security reasons.

就我而言,我使用BrowserRouter,并发现我要么需要运行本地服务器或交换机来HashRouter,因为BrowserRouter不以工作file://路径,由于安全方面的原因。

https://github.com/ReactTraining/react-router/issues/6533#issuecomment-451969973

https://github.com/ReactTraining/react-router/issues/6533#issuecomment-451969973

回答by Jaspreet Singh

You are using BrowserRouterwhich uses HTML5 history API(window.history), unlike Routerand HashRouter.

您正在使用BrowserRouter哪个使用 HTML5 历史 API( window.history),与Router和不同HashRouter

Mapping of BrowserRouter's history.pushmethod to HTML5 history is below:

BrowserRouter 的history.push方法到 HTML5 历史的映射如下:

this.props.history.push({
  pathname: '/create',
  state: { addExpense: this.addExpense }
});

pathname('/create')> window.history.push('create')

pathname('/create')> window.history.push('create')

state({ addExpense: this.addExpense })> window.history.pushState({ addExpense: this.addExpense })

state({ addExpense: this.addExpense })> window.history.pushState({ addExpense: this.addExpense })

The actual issue is with window.history.pushStateas it stores the state as a stringand has size limit of 640k characters.

实际问题在于window.history.pushState它将状态存储为 astring并且大小限制为640k 个字符

Source: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

来源https: //developer.mozilla.org/en-US/docs/Web/API/History/pushState