为什么`当使用来自react-router-dom的`Link`时,'历史''上执行'pushState'失败? [英] Why `Failed to execute 'pushState' on 'History'` when using `Link` from react-router-dom?

查看:88
本文介绍了为什么`当使用来自react-router-dom的`Link`时,'历史''上执行'pushState'失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过类似的帖子,但找不到答案,在我的情况下,我正试图从< App /> 传递一个动作:

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

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

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

to /create route where I'm rendering <AddExpenseForm /> component

<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?

Index.js中的路线:

Routes in 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>
        ...


推荐答案

首先,在 addExpense 函数中添加一些默认值:

Firstly, add some default value to your addExpense function:

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

然后使用链接

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

尝试此操作(更好的方法):

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

下一步(创建)组件使用传递的值,如下所示:

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

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

这篇关于为什么`当使用来自react-router-dom的`Link`时,'历史''上执行'pushState'失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆