【问题标题】:react router redux url反应路由器redux url
【发布时间】:2018-01-14 05:13:10
【问题描述】:

我正在使用 react、react router v4 和 redux/react-router-redux 制作我的第一个 Web 应用。

这是一个购物网站。我在商店中保存了我的产品列表,并且可以正常访问它们。我已经制作了一个产品列表页面,当单击产品的图像时,我有路由设置将我带到一个新的 url(/'productmodel')。

目前我有一个“ProductPage”组件,我已经为我的路由器中的每个相应路由传递了与特定产品相关的道具。这似乎是一个很长的路要走。

我想做的是为每个路由渲染,然后让 ProductPage 组件本身,根据路由(URL 地址)渲染正确的产品。

最好的方法是什么?

提前谢谢你:)

【问题讨论】:

  • 上帝保佑你使用这些库。请考虑您是否真的需要reduxreact-router。在 SPA 中,有时只需 react-router 就足够了。在你真正需要的时候考虑使用redux,而不是因为有人告诉你它很好。
  • 你好,浩棠,谢谢你的鼓励。我使用了 redux,因为在我的产品列表页面中,我有过滤器,可以让我按品牌、价格范围等进行过滤。redux 似乎是这样做的最佳选择,而且现在我使用它确实是一个好方法。

标签: reactjs redux browser-history react-router-v4


【解决方案1】:

好的,所以我设法做到了!

我创建了一个 ProductPageContainer 以便从商店传递我的产品列表:

function mapStateToProps(state) {
    let products = state.kitsProducts;
    return {
    products: products
    };
};

然后,在我的组件中,我从参数中获取了 productid;正如侯赛因所建议的:

createProductPageComponent() {
    let activeProduct = this.props.products.filter(product => product.id === this.props.match.params.productid)
    return activeProduct.map(product =>{
        return (
            <ProductPage
                key={product.id}
                brand={product.brand}
                productName={product.model.toUpperCase()}
                price={"£"+product.price}
                productImage={product.image}
                text={product.text}
            />
        )
    })
}

现在我的产品页面呈现到正确的路线,这取决于在上一个产品列表页面中选择了哪个产品。以及正确的产品,取决于它被渲染的路线。

谢谢侯赛因!!!你对我的帮助超出了你的想象!

【讨论】:

    【解决方案2】:

    你在追求这样的事情吗?

    产品列表页面:

    ....
    
    render() {
       <div>
           {this.props.products.map(product => 
               <Link key={product.id} to={"/product/"+product.id}>
                   {product.name}
               </Link>
           )}
       </div> 
    }
    
    ....
    

    产品页面:

    ....
    
    componentWillMount() {
        this.props.actions.getProduct(this.props.match.params.productid);
    }
    
    ....
    
    render() {
       <div>
           <span>{this.props.product.name}</Link>
       </div> 
    }
    ....
    

    您的产品页面路径如下所示:

    <Route exact path="product/:productid" component={ProductPage} />
    

    所以这里发生的情况是,当您在“产品列表”页面上单击产品时,您会被重定向到以产品 ID 作为参数的产品页面。在产品页面上的组件挂载上,您从参数(url)中检索传递 productid 的产品。

    【讨论】:

    • 哇,感谢侯赛因,这似乎是一个很好的方法。并且不需要我将我的历史记录连接到我的 redux 商店。完成后,我将尝试一下,然后回到这篇文章!
    • 好的,所以这对我来说并不容易。我无法使用 getProduct 函数。我想要做的是从我的产品减速器(产品列表)中检索与路线路径相关的产品,然后我只想渲染这个产品。我看到我可以从我的组件中访问参数,我仍然在努力如何告诉我的组件只使用与参数匹配的产品。使用 connectedRouter 和 routerReducer 对我没有帮助吗?
    猜你喜欢
    • 2016-08-24
    • 2023-03-06
    • 2017-11-06
    • 1970-01-01
    • 2020-08-24
    • 2018-05-30
    • 2017-11-15
    • 2018-09-04
    • 2018-07-07
    相关资源
    最近更新 更多