首页 > 解决方案 > 仅当我单击链接时出现 DataCloneError

问题描述

我对做出反应非常陌生,并且正在尝试尽我所能来处理 JS。

我正在 React 中创建一个食谱应用程序。我Linkreact-router-dom包中添加。我在同一个组件(导航栏组件)中使用了 3 次。两个链接正常工作,但第三个链接没有。当我点击它时,我收到以下错误:

DataCloneError:无法在“历史”上执行“pushState”:...

此错误消息后的文本显示了我在App.js文件中的一个函数。

奇怪的是,当我导航到链接到通过地址栏给我错误的链接时,它工作正常。我认为正在发生的事情是该PushState()方法试图将重复的对象推送到全局对象history上的对象中window,但我不知道如何解决这个问题。

我想要做的是将App.js文件中的方法传递给另一个组件,但我想总体问题是,“为什么我会收到这个错误?”

应用程序.js

class App extends Component {
state = {
    recipes: [ //an array of objects ]
}

handleAddRecipe = recipe => {. <-- Method to pass as prop
    *Does stuff*
  };

  render() {
    return (
      <React.Fragment>
        <Router>
          <Navbar
            *other props*
            handleAddRecipe={this.handleAddRecipe}
          />
          <Switch>
            <Route path="/" exact component={Main} />
            <Route path="/add-recipe" component={RecipeForm} />
            <Route path="/recipes" component={Recipes} />
          </Switch>
        </Router>
        <Footer />
      </React.Fragment>
    );
  }
}

导航栏.js

class Navbar extends Component {
  render() {
    return (
      <nav className="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
        <Link to="/" exact="true" className="navbar-brand"> <--THIS LINK WORKS
          Recipe Maker
    </Link>

    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav mr-auto">
        <Link <--------THIS LINK DOES NOT WORK. Clicking this link produces the error mentioned above.
          className="nav-link"
          to={{
            pathname: "/add-recipe",
            state: {
              handleAddRecipe: this.props.handleAddRecipe
            }
          }}
        >
          <li className="nav-item active">
            Create Recipe <span className="sr-only">(current)</span>
          </li>
        </Link>

        <Link <--THIS LINK WORKS
          className="nav-link"
          to={{
            pathname: "/recipes",
            state: {
              recipes: this.props.recipes
            }
          }}
          tabIndex="-1"
        >
          <li className="nav-item">
            View Recipes ({this.props.numOfRecipes})
          </li>
        </Link>
      </ul>
    </div>
  </nav>
);
}
}

标签: javascriptreactjsbrowser-historypushstate

解决方案


推荐阅读