【问题标题】:i cannot make button sort by json in react我无法在反应中按 json 排序按钮
【发布时间】:2020-08-22 14:51:14
【问题描述】:

我想要一个按钮,点击它时按价格对产品进行排序

  state = {
    products: storeProducts,
  };
  render() {
    return (
      <React.Fragment>
        <ProductWrapper className="py-5">
          <div className="container">
            <Title name="our" title="products" />
            <select>
              <option value="price">Price</option>
              <option value="name">Name</option>
            </select>
            <div className="row">
              <ProductConsumer>
                {(value) => {
                  return value.products.map((product) => {
                    return <Product key={product.id} product={product} />;
                  });
                }}
              </ProductConsumer>
            

const ProductWrapper = styled.section``;

我尝试了几种方法,但都没有奏效 https://5f3f90843848e739f77ff21f--react-e-commerce-store-excercise.netlify.app/这里是网站

这是数据

export const storeProducts = [
 {
   id: 1,
   title: "Samsung 20 plus",
   img: "img/20plus.png",
   price: 1197,
   company: "Samsung",
   info:
     "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green gentrify.",
   inCart: false,
   count: 0,
   total: 0,
 },
 {
   id: 2,
   title: "Samsung 20ultra",
   img: "img/20ultra.png",
   price: 1391,
   company: "SAMSUNG",
   info:
     "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juigentrify.",
   inCart: false,
   count: 0,
   total: 0,

 }

];

【问题讨论】:

    标签: json reactjs


    【解决方案1】:

    这应该对你有帮助

    onClick = () => {
        let newprod_list = this.state.products.sort((a,b) => {
            if (a.price < b.price) return -1;
            if (a.price === b.price) return 0;
            return 1;
        });
        this.setState({products:newprod_list});
    }
    

    将此函数分配给按钮的 onClick 侦听器(按升序排序)

    你可能想把你的渲染函数编辑成类似..

    <ProductConsumer>
    {this.state.products.map(v => <Product key={v.id} product={v} />)}
    </ProductConsumer>
    

    【讨论】:

    • 你需要newprod_list in this.setState({products:newprod_list }); 而不是this.setState({products:newprod}); 对吧?
    • 也许最后一个if (a.price === b.price) return 1; 可以只是return 1;,因为其他的都已经处理好了?
    • 是的。它应该是 newprod_list 。抱歉打错了。是的。它可以只是return 1。我这样做是为了方便读者。感谢@SafaLabash 的反馈尝试更新编辑
    • 确保this.state.products 是一个数组。 sort 应该在数组上工作。
    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2021-10-07
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多