【问题标题】:Filter redux state based on specific url to display one product and it's variations根据特定 url 过滤 redux 状态以显示一个产品及其变体
【发布时间】:2019-04-15 21:48:03
【问题描述】:
我目前正在建立一个基于 drupal 的电子商务响应站点。我已经将它设置为在我的反应应用程序中进行 api 调用和存储数据。当我控制台日志时,我得到了我当前的 3 种产品,并且得到了所有产品变体的另一个数组。这一切都在该州。
另外,我有一个显示产品详细信息的页面。它显示描述、颜色选项、尺寸选项等。现在我已经设置好了,当我从应用程序中的产品选择器中单击链接时,它会移动到产品页面,其中包含我单击的产品名称的 url并显示正确的产品描述。但是,我需要对其进行过滤,以便 redux 状态仅包含该产品及其相关变体。希望这是有道理的......
不确定你们需要从应用程序中看到什么才能理解我的问题,所以请告诉我,我会添加它们以澄清。谢谢!
【问题讨论】:
标签:
javascript
reactjs
drupal
redux
react-redux
【解决方案1】:
由于您没有提供代码的任何部分,我假设了其中的一部分。
我希望这会有所帮助:
class ProductPage extends Component {
constructor(props) {
super(props);
this.state = { productDetails: {}, relatedProducts: [] };
}
componentDidMount() {
// considering your product URL looks like domain.com/product/product-name
const productName = window.location.pathname.split('/')[2];
const productDetails = this.props.productList.find(product => product.name === productName);
const relatedProducts = this.props.productList.filter(product => // determine how a product can be considered as related to the current product);
this.setState({ productDetails, relatedProducts });
}
render() {
// render codes...
}
}
export default connect(
state => ({
productList: state.products // or whatever the name of your reducer for your product list in redux store
})
)(ProductPage);