【问题标题】:How can I render a component in React to 2 different components?如何将 React 中的组件渲染为 2 个不同的组件?
【发布时间】:2019-06-01 23:58:59
【问题描述】:

我正在开发一个 ReactJS 项目。我在主页“索引组件”中有3个组件如下,

导航- 精选- 页脚

我的导航组件有 2 个链接到 2 个不同的组件。 我的Switch如下,

  <Switch>
      <Route path="/home" component={props => <Index {...props} />} />
      <Route path="/register" component={Register} />
      <Route path="/login" component={Login} />
      <Route path="/cart" component={Cart} />
      <Redirect from="/" to="home" />
  </Switch>

我的索引组件也如下,

   <React.Fragment>
       <Search />
       <Nav history={history} />
    {this.homePageComponents()}
       <Route
      path="/home/bedding"
      component={props => (
        <Bedding beddingProducts={this.beddingProducts()} {...props} />
      )}
    />
       <Route
      path="/home/bath"
      component={props => (
        <Bath bathProducts={this.bathProducts()} {...props} />
      )}
    />
       <Route path="/home/search" component={Search} />
  </React.Fragment>

我正在尝试将 Nav 组件渲染到 Bath 和 Bedding 产品,但每当我导入它并在那里使用它时,它都会给我一个错误,说 this.props.history.replace 未定义。 这是项目的链接。 https://github.com/MaxOffline/beetle

【问题讨论】:

  • 请提供错误。
  • 这是说 this.props.history.replace 是未定义的

标签: javascript reactjs


【解决方案1】:

我认为您可以使用 react-router 提供的“withRouter”包装器组件来包装您的导航组件来解决您的问题。

https://reacttraining.com/react-router/web/api/withRouter

【讨论】:

  • 谢谢,这就是我要找的。​​span>
  • 很高兴它对你有所帮助 :)
【解决方案2】:

如果您在 nav.jsx 的 render 方法中 console.log(this.props),您会看到它包含一个历史对象,但该对象上没有替换方法。

您可能正在寻找this.props.history.push 方法?

【讨论】:

  • 还是未定义
【解决方案3】:

我找到了一个非常简单的方法来解决这个问题。 我需要做的就是有条件地将组件渲染到主页,因此我只需将以下帮助方法添加到我的“索引”组件中。

homePageComponents = () => {
const featuredProducts = this.state.products.filter(
  product => product.featured === true
);
if (this.props.history.location.pathname === "/home") {
  return <Featured featuredProducts={featuredProducts} />;
}

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-07
    • 2018-12-08
    • 2015-11-03
    • 1970-01-01
    • 2022-12-19
    • 2019-06-03
    • 2017-10-06
    • 2018-09-10
    相关资源
    最近更新 更多