如何设置状态

时间:2020-10-04 20:14:31

标签: javascript reactjs web redux

晚上好

我反应很新,正在建立我的第一个主要项目。我想做以下事情: 当用户选择特定尺寸的产品时,我想更改项目状态的值。当用户选择尺寸时,只有该尺寸的产品应出现在屏幕上。 我应该做的最后一件事是在用户更改大小时设置状态,但是我无法做到这一点:

我的代码:

import React, { Component, useEffect, useState } from 'react'
import { listProduct } from '../../actions/productActions'
import { useDispatch, useSelector } from 'react-redux'

const Filter = () => {
  const productList = useSelector((state) => state.productList)
  const { products } = productList
  const dispatch = useDispatch()
  const [items, setItem] = useState([])

  useEffect(() => {
    dispatch(listProduct())
    setItem(products)
  }, [])

  console.log(items)

  const handleChange = (e) => {
    if (e.target.value === 'S') {
      return console.log(products.filter((item) => item.size === 'S'))
    } else if (e.target.value === 'XS') {
      return console.log(products.filter((item) => item.size === 'XS'))
    } else if (e.target.value === 'M') {
      return console.log(products.filter((item) => item.size === 'M'))
    } else if (e.target.value === 'L') {
      return console.log(products.filter((item) => item.size === 'L'))
    } else if (e.target.value === 'XL') {
      return console.log(products.filter((item) => item.size === 'XL'))
    } else {
      return console.log(products)
    }
  }

  return (
    <div className="filter">
      <label>
        Order:
        <select>
          <option value="lowest">Lowest to Highest</option>
          <option value="highest">Highest to Lowest</option>
        </select>
      </label>
      <label>
        Size:
        <select className="size" onChange={handleChange}>
          <option value="">ALL</option>
          <option value="XS">XS</option>
          <option value="S">S</option>
          <option value="M">M</option>
          <option value="L">L</option>
          <option value="XL">XL</option>
        </select>
      </label>
    </div>
  )
}

export default Filter

3 个答案:

答案 0 :(得分:0)

您要返回:

return (
              console.log(products.filter(item =>item.size === "S"  ) ) 
                 
            )

console.log()当然对实际组件状态没有影响。 尝试使用setItem(products)更新状态

答案 1 :(得分:0)

这就是我制造产品组件的地方:

import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { Library } from '@fortawesome/fontawesome-svg-core'
import { faShoppingBasket } from '@fortawesome/free-solid-svg-icons'
import { useDispatch, useSelector } from 'react-redux'
import Filter from './filter'
import { listProduct } from '../../actions/productActions'

function Product(props) {
  //default value is an array, because we've got data in an array
  const [qty, setQty] = useState(1)
  const productList = useSelector((state) => state.productList)

  const { products, loading, error } = productList
  const dispatch = useDispatch()
  const [items, setItems] = useState()

  useEffect(() => {
    dispatch(listProduct())
  }, [])

  // handlefilter

  // handle cart adding
  const handleAddToCart = () => {
    props.history.push('/cart/' + props.match.params.id + '?qty' + qty)
  }

  return (
    // Check the loading before rendering products
    loading ? (
      <div>
        <h1 className="load">loading...</h1>
      </div>
    ) : error ? (
      <div>{error}</div>
    ) : (
      <ul className="products">
        {products.map((product) => (
          <li key={product.id} className="product">
            <Link to={'/product/' + product.id}>
              <div
                className="img"
                style={{
                  background: `url(${product.img})`,
                  backgroundSize: 'cover',
                }}
              ></div>
            </Link>
            {/* LOOK OUT FOR TYPOS IN ROUTIING  dont put':' after /, this only applies
                       when routing because the ": " implies for a parameter
                       In this case you can directly access product.id  */}
            <Link to={'/product/' + product.id}>
              <h1>{product.name}</h1>
            </Link>
            <p>
              {' '}
              <small>€</small>
              {product.price}
            </p>
            <div>size: {product.size}</div>

            {product.qty > 0 ? (
              <div>
                <button onClick={handleAddToCart}>Add to cart</button>{' '}
                <div>{product.qty} left</div>
              </div>
            ) : (
              <div>out of stock</div>
            )}
          </li>
        ))}
      </ul>
    )
  )
}
export default Product

所以我想根据所选尺寸渲染特定产品

答案 2 :(得分:0)

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const products = [
    { size: "S" },
    { size: "S" },
    { size: "XS" },
    { size: "XS" },
    { size: "M" },
    { size: "M" },
    { size: "L" },
    { size: "L" },
    { size: "XL" },
    { size: "XL" }
  ];
  const [items, setItem] = useState([]);

  useEffect(() => {
    setItem(products);
  }, []);

  const handleChange = ({ target: { value } }) => {
    let filteredProducts = [];
    filteredProducts =
      value === "ALL"
        ? [...products]
        : products.filter((item) => item.size === value);

    console.log(value);

    setItem(filteredProducts);
  };

  return (
    <div className="filter">
      <label>
        Order:
        <select>
          <option value="lowest">Lowest to Highest</option>
          <option value="highest">Highest to Lowest</option>
        </select>
      </label>
      <label>
        Size:
        <select className="size" onChange={handleChange}>
          <option value="ALL">ALL</option>
          <option value="XS">XS</option>
          <option value="S">S</option>
          <option value="M">M</option>
          <option value="L">L</option>
          <option value="XL">XL</option>
        </select>
      </label>

      <ul>
        {items.map((p) => (
          <li>{p.size}</li>
        ))}
      </ul>
    </div>
  );
}

您只需要将过滤后的数组传递给setItems并以html形式呈现项目。