【问题标题】:Why `Failed to execute 'pushState' on 'History'` when using `Link` from react-router-dom?为什么在使用 react-router-dom 中的“Link”时“无法在“History”上执行“pushState”?
【发布时间】:2018-03-29 17:46:57
【问题描述】:

我看过类似的帖子,但找不到答案,就我而言,我正在尝试从<App />传递一个动作:

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

/create 我正在渲染<AddExpenseForm /> 组件的路由

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

App.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>
        ...

【问题讨论】:

  • 尝试签出this similar question。也许也尝试不将addExpense() 函数推送到状态。我怀疑这个问题是您最近试图解决的先前问题的一个分支,关于在路线之间传递道具。请参阅我对此的回答以获取更多信息。
  • 感谢您的链接。我已经看到了这个解释,但有解决方案吗? “使用 sessionStorage 和/或 localStorage”。在这种情况下,我该如何实现?我是个新手。
  • 对缺乏明确性表示歉意。该解决方案保留在 ReactJS / React Router 之前。不是适合您的用例的实现,但对于理解错误仍然有用。

标签: javascript reactjs react-router


【解决方案1】:

在我的情况下,这是由于尝试路由到具有两个 "/" 字符的路径引起的。我是这样写的:

history.push(`${location.pathname}/somePath`);

...但是如果location.pathname"/" 则会尝试转到"//somePath",从而导致错误,

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,但是当我将所有反斜杠更改为如下所示的正斜杠时,错误得到了解决:-

     <li><NavLink to="/">Home</NavLink></li>
                   <li><NavLink to="/About">About</NavLink></li>
                   <li><NavLink to="/Contact">Contact</NavLink></li>
    

    【讨论】:

      【解决方案3】:

      您正在使用 BrowserRouter,它使用 HTML5 历史 API(window.history),与 RouterHashRouter 不同。

      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

      【讨论】:

        【解决方案4】:

        就我而言,我使用的是BrowserRouter,但发现我需要运行本地服务器或切换到HashRouter,因为出于安全原因,BrowserRouter 不适用于file:// 路径。

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

        【讨论】:

          【解决方案5】:

          首先,为您的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 }
              });
            }
          

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

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

          【讨论】:

          • 谢谢,如何实现 goToNextPage?我用onClick={this.goToNextPage}创建了一个按钮,但出现错误Cannot read property 'props' of undefined
          • @karolis2017 使用fat arrow '=&gt;' 或使用{this.goToNextPage.bind(this)}。还更新了我的答案。
          • 现在得到这个DataCloneError: Failed to execute 'pushState' on 'History': [object Object] could not be cloned.
          • 你能复制你的问题here吗?
          • 如何在 codepen 中做路由?我该怎么办import from 'react-router-dom';
          猜你喜欢
          • 2019-11-25
          • 2015-03-24
          • 2020-09-27
          • 2021-07-14
          • 2020-07-11
          • 1970-01-01
          • 1970-01-01
          • 2019-09-15
          • 2021-05-07
          相关资源
          最近更新 更多