根据特定 url 过滤 redux 状态以显示一种产品及其变体

Filter redux state based on specific url to display one product and it's variations

我目前正在建立一个基于 drupal 的电子商务反应网站。我已经将其设置为在我的 React 应用程序中进行 api 调用和存储数据。当我控制日志时,我得到了我当前的 3 个产品,并且我得到了另一个包含所有产品变体的数组。州里都有。

此外,我有一个显示产品详细信息的页面。它显示描述、颜色选项、尺寸选项等。现在我已经设置好了,当我从我的应用程序中的产品选择器中单击 link 时,它会移动到带有 url 的产品页面包含我点击的产品名称并显示正确的产品描述。但是,我需要对其进行过滤,以便 redux 状态仅包含该产品及其相关变体。希望这是有道理的...

不确定你们需要从应用程序中看到什么才能理解我的问题,所以请告诉我,我会添加它们来澄清。谢谢!

由于您没有提供任何部分代码,我假设了其中的一部分。

希望对您有所帮助:

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);