reactjs 我需要按周数过滤这些卡,我不知道如何开始

b1uwtaje  于 2023-02-22  发布在  React
关注(0)|答案(2)|浏览(87)

例如!我需要创建3个单选按钮,如果我点击1-4,我将需要看到有1到4周的锻炼,如果我点击5-9,我需要看到有5到9周的锻炼!
我如何修复代码并创建它?
这是我的准则!

import React, { useState, useEffect, useContext } from "react";
import { Link } from "react-router-dom";
import "../../styles/workoutLibStyle.css";
import { Context } from "../store/appContext";

import {
  CDBSidebar,
  CDBSidebarContent,
  CDBSidebarHeader,
  CDBSidebarMenu,
  CDBSidebarMenuItem,
  CDBSidebarFooter,
} from "cdbreact";

export const Workouts = () => {{}
  const { store, actions } = useContext(Context);
  const [searchName, setSearchName] = useState("");
  const [selectedDifficulty, setSelectedDifficulty] = useState("");
  const [selectedWeeks, setSelectedWeeks] = useState("");

function filterByWeeks(elements) {
  const oneToFour = elements.filter(element => element.weeks >= 1 && element.weeks <= 4 ? true : false);
  const fiveToNine = elements.filter(element => element.weeks >= 5 && element.weeks <= 9 ? true : false);
  const moreThanTen = elements.filter(element => element.weeks > 10 ? true : false);
  
  return [oneToFour, fiveToNine, moreThanTen];
}

  useEffect(() => {
    async function fetchData() {
      actions.getList("workouts");
    }
    fetchData();
  }, []);

  const inputSearch = (event) => {
    setSearchName(event.target.value);
  };

  const inputDifficulty = (event) => {
    setSelectedDifficulty(event.target.value);
  };

   const inputWeeks = (event) => {
    setSelectedWeeks(event.target.value);
  };

  return (
    <>
      <div className="workout-main-container">
        <div>
          {/* Start Sidebar */}
          <CDBSidebar
            toggled="false"
            textColor="#333"
            backgroundColor="#f0f0f0"
            className="workout-sidebar-title sidebar-height "
          >
            <CDBSidebarHeader prefix={<i className="fa fa-bars " />}>
              Find the Workout or Coach
            </CDBSidebarHeader>
            <CDBSidebarContent>
              <CDBSidebarMenu>
                <CDBSidebarMenuItem icon="search">
                  <input
                    className="form-control mr-sm-2"
                    type="text"
                    placeholder="Type to search..."
                    value={searchName}
                    onChange={inputSearch}
                  />
                </CDBSidebarMenuItem>
                <CDBSidebarMenuItem icon="sticky-note">
                  Filter by Difficulty
                </CDBSidebarMenuItem>
                <CDBSidebarMenuItem className="mx-5 my-2">
                  <div>
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="radio"
                        name="difficulty"
                        id="easy"
                        value="Easy"
                        checked={selectedDifficulty === "Easy"}
                        onChange={inputDifficulty}
                      />
                      <label
                        className="form-check-label"
                        htmlFor="exampleRadios1"
                      >
                        Easy
                      </label>
                    </div>
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="radio"
                        name="difficulty"
                        id="medium"
                        value="Medium"
                        checked={selectedDifficulty === "Medium"}
                        onChange={inputDifficulty}
                      />
                      <label
                        className="form-check-label"
                        htmlFor="exampleRadios2"
                      >
                        Medium
                      </label>
                    </div>
                    <div className="form-check disabled">
                      <input
                        className="form-check-input"
                        type="radio"
                        name="difficulty"
                        id="hard"
                        value="Hard"
                        checked={selectedDifficulty === "Hard"}
                        onChange={inputDifficulty}
                      />
                      <label
                        className="form-check-label"
                        htmlFor="exampleRadios3"
                      >
                        Hard
                      </label>
                    </div>
                  </div>
                </CDBSidebarMenuItem>
                <CDBSidebarMenuItem icon="calendar">
                  Filter by Weeks
                </CDBSidebarMenuItem>
                  
                <CDBSidebarMenuItem className="mx-5 my-2">
                  <div>
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="radio"
                        name="weeks"
                        id="1-4"
                        value="1-4"
                        checked={selectedWeeks === "1-4"}
                        onChange={inputWeeks}
                      />
                      <label
                        className="form-check-label"
                        htmlFor="exampleRadios1"
                      >
                        1-4
                      </label>
                    </div>
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="radio"
                        name="weeks"
                        id="5-9"
                        value="5-9"
                        checked={selectedWeeks}
                        onChange={inputWeeks}
                      />
                      <label
                        className="form-check-label"
                        htmlFor="exampleRadios2"
                      >
                        5-9
                      </label>
                    </div>
                    <div className="form-check disabled">
                      <input
                        className="form-check-input"
                        type="radio"
                        name="weeks"
                        id="10+"
                        value="10+"
                        checked={selectedWeeks}
                        onChange={inputWeeks}
                      />
                      <label
                        className="form-check-label"
                        htmlFor="exampleRadios3"
                      >
                        10+
                      </label>
                    </div>
                  </div>
                </CDBSidebarMenuItem>

              </CDBSidebarMenu>

            </CDBSidebarContent>

            <CDBSidebarFooter
              style={{ textAlign: "center" }}
            ></CDBSidebarFooter>
          </CDBSidebar>
          {/* Aca Finaliza el Sidebar */}
        </div>
        <div className="d-flex-column w-100 justify-content-center">
          <h1 className="page-title text-center my-4 page-title-workoutLib w-100">
            Workout Library
          </h1>

          <div className="container">
            <div className="row ">
              {store.workouts?.filter((element) => element.name.toLowerCase().includes(searchName.toLowerCase()) ||
                element.coach_name.toLowerCase().includes(searchName.toLowerCase())
              ).filter((element) => selectedDifficulty ? element.difficulty === selectedDifficulty : true).filter((element) => selectedWeeks ? element.weeks >= 1 && element.weeks <= 4 : true).map((element, index) => (
                <div
                  className="col-sm-12 col-md-6 col-lg-4 col-xl-3 my-3"
                  key={element.id || index}
                >
                  <div className="card">
                    <h5 className="card-title-section text-center title-container">
                      {element.name}
                    </h5>
                    <ul className="list-group list-group-flush list-group-workouts">
                      <li>
                        <img
                          className="workout-library-img"
                          src={element.wk_image}
                          alt="Workout Image"
                        />
                      </li>
                      <li className="list-group-item workout-item workout-description bg-light ">
                        {element.description}
                      </li>
                      <li className="list-group-item workout-item">
                        <i className="fa-solid fa-calendar-day mx-2"></i>
                        <span>Days per week: </span>
                        {element.days_per_week}
                      </li>
                      <li className="list-group-item workout-item bg-light ">
                        <i className="fa-solid fa-calendar-days mx-2"></i>
                        <span>Weeks: </span>
                        {element.weeks}
                      </li>
                      <li className="list-group-item workout-item ">
                        <i className="fa-solid fa-square-poll-vertical mx-2"></i>
                        <span>Difficulty: </span>
                        {element.difficulty}
                      </li>
                      <li className="list-group-item workout-item bg-light ">
                        <i className="fa-solid fa-user mx-2"></i>
                        <span>Coach: </span>
                        {element.coach_name}
                      </li>
                    </ul>
                  </div>
                  <div className="btn-container-workouts my-3">
                    <Link
                      to="#"
                      className="btn btn-warning btn-workout-library"
                    >
                      Buy
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

我不知道如何开始,所以谢谢你,如果你能帮助我

fhg3lkii

fhg3lkii1#

这是示例中的Array

const workoutArray = [
{ id: 1, day: "Monday", name: "Push-Ups", weeks: 1 },
{ id: 2, day: "Tuesday", name: "Squats", weeks: 15 },
{ id: 3, day: "Wednesday", name: "Plank", weeks: 4 },
{ id: 4, day: "Thursday", name: "Lunges", weeks: 20 },
{ id: 5, day: "Friday", name: "Crunches", weeks: 8 },
{ id: 6, day: "Saturday", name: "Burpees", weeks: 15 },
{ id: 7, day: "Sunday", name: "Rest day", weeks: 12 }];

现在定义一个状态

const [workouts, setWorkouts] = useState(workoutArray);

然后按周筛选数组

const oneToFour = workoutArray.filter(
(element) => element.weeks >= 1 && element.weeks <= 4);

 const fiveToNine = workoutArray.filter(
(element) => element.weeks >= 5 && element.weeks <= 9);

 const moreThanTen = workoutArray.filter((element) => element.weeks > 10);

并返回渲染

return (
<div>
  <div>
    <label>
      <input
        type="radio"
        name="weekFilter"
        value="1-4"
        onChange={() => setWorkouts(oneToFour)} // this line sets the workout state with the filtered earlier from 1 to 4 weeks
      />
      1-4 weeks
    </label>
    <label>
      <input
        type="radio"
        name="weekFilter"
        value="5-9"
        onChange={() => setWorkouts(fiveToNine)} // this line sets the workout state with the filtered earlier from 5 to 9 weeks
      />
      5-9 weeks
    </label>
    <label>
      <input
        type="radio"
        name="weekFilter"
        value="10+"
        onChange={() => setWorkouts(moreThanTen)} // this line sets the workout state with the filtered earlier to 10+
      />
      More than 10 weeks
    </label>
  </div>
    <ul>
    {workouts.map((workout) => (
      <li key={workout.id}>
        {workout.name} - {workout.weeks}
      </li>
    ))}
  </ul>
</div>);
0tdrvxhp

0tdrvxhp2#

您必须创建一个像workousFilterByWeeks这样的变量,您可能希望使用useMemo来避免不必要的重新呈现,因为您的组件中有很多状态

const workoutsFilteredByWeeks = useMemo(() => {
  const { upperLimit, lowerLimit } = getLimits(filterOption);
  return workouts.filter(
    (element) =>
      element.weeks >= lowerLimit &&
      (!upperLimit || element.weeks <= upperLimit ? true : false)
  )
}, [workouts, filterOption]);

另外,你可以创建一个函数来获取取决于选项的限制,让事情变得更清楚。这里有一个sandbox,你可以检查所有的代码。

相关问题