Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

reactjs - how to filter a componet by id in react js

I am learn reactjs and hand one project,but I could not completely fiddle some branch of the whole.I post the code below: in the App.js:import React, { useState } from "react";

import colorData from "./color-data.json";
import ColorList from "./ColorList.js";

export default function App() {
  const [colors, setColors] = useState(colorData);

  const removeColor = id => {
    const newColors = colors.filter(color => color.id !== id);
    setColors(newColors);
  };

  const rateColor = (id, rating) => {
    const newColors = colors.map(color =>
      color.id === id ? { ...color, rating } : color
    );
    setColors(newColors);
  };

  return (
    <ColorList
      colors={colors}
      onRemoveColor={removeColor}
      onRateColor={rateColor}
    />
  );
}

what is the "color => color.id !== id" used for?are they not the same: "color.id" and "id" it is the project link:https://codesandbox.io/s/learning-react-color-organizer-2-forked-ke1gz?file=/src/App.js

question from:https://stackoverflow.com/questions/65649795/how-to-filter-a-componet-by-id-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

color => color.id !== id is a predicate that's used to remove the color of the id that is passed to your removeColor function.

How this works is the filter function will iterate through each item of the array (colors in this example) and pass that item to a function you provide to check if it should be removed from the list. If the function is true, it's removed.

color => color.id !== id is the function that's called for each item, so if the current color's id equals the id that is passed to the removeColor function, then it's removed.

One thing to note is the original array isn't changed, it just returns a new array (newColors) with the items removed.

// function that takes an id as a parameter
const removeColor = id => {
  // remove the color of the id that is passed by using the filter function
  const newColors = colors.filter(color => color.id !== id);
  // update your state with filtered colors
  setColors(newColors);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...