【问题标题】:React Router v4 not rendering component in route w/ parametersReact Router v4 没有在带有参数的路由中渲染组件
【发布时间】:2018-10-11 23:54:46
【问题描述】:

我正在一个电子商务网站上做一个项目,目前为"/" 的主页和"/:id" 的产品列表页面设置了正确的路由。我正在尝试为单个产品页面设置路由,但是 react-router 根本不呈现我的组件。

索引.js

ReactDOM.render((
  <BrowserRouter>
    <App />
  </BrowserRouter>), document.getElementById('root'));
  registerServiceWorker();

App.js

<Switch>
  <Route exact path="/" render={()=> apiDataLoaded ? <HomeLayout data={data}/> : <div>Loading...</div>}/>
  <Route path="/:id" render={(props)=> <ProductListLayout {...props} />} />
</Switch>

列表组件

return (
  <Switch>
    <div className="product-list-item-card">
      <div className="product-list-item-img" style={bgImage}></div>
      <div className="product-list-item-content">
        <div className="product-list-item-overlay">
          <Link to={`/products/${id}`}>
              <DetailsBtn />
          </Link>
        </div>
        <h3>{name}</h3>
        <h6>{brand}</h6>
        <span>${msrp}</span>
        <p>${sale}</p>
      </div>
    </div>
    <Route path={'/products/:product_id'} render={()=> <div>Product Page</div>}/>
  </Switch>
)}

在上面的列表组件中,当我点击链接时,url 是唯一改变的东西吗?关于我做错了什么的任何想法?谢谢。

已解决

在 App.js 中更改路由的顺序只是解决方案的一部分。我还将我的路由从列表组件移动到路由顺序顶部的 App.js,现在它可以工作了!

新的 App.js

<Switch>
  <Route path={`/products/:product_id`} component={ProductLayout} />
  <Route path="/:id" render={(props)=> <ProductListLayout {...props} />} />
  <Route exact path="/" render={()=> apiDataLoaded ? <HomeLayout data={data}/> : <div>Loading...</div>}/>
</Switch>

【问题讨论】:

    标签: javascript reactjs react-router react-router-v4


    【解决方案1】:

    移除开关并在ProductListLayout组件中使用div

    ProductListLayout.js

    const ProductListLayout = () => {
      return (
        <div>
          <div className="product-list-item-card">
            <div className="product-list-item-img"></div>
            <div className="product-list-item-content">
              <div className="product-list-item-overlay">
                <Link to={`/products/${99999}`}>
                  Click here
                </Link>
              </div>
              <h3>{name}</h3>
            </div>
          </div>
          <Route exact path={`/products/:product_id`} render={()=> <div>Product Page</div>}/>
        </div>
      );
    }
    

    Click here for more detail

    【讨论】:

      【解决方案2】:

      您只需要更改当前路线上的位置...

      <Switch>
       <Route path="/:id" key={1} render={(props)=> <ProductListLayout 
         {...props} />} />
       <Route exact path="/"  key={1} render={()=> apiDataLoaded ? 
         <HomeLayout data= . 
         {data}/> : <div>Loading...</div>}/>
      </Switch>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-18
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 2018-02-10
        相关资源
        最近更新 更多