简体   繁体   English

在反应中单击按钮时过滤 json 数据

[英]Filter json data when click button in react

i have a json file as a server, i need filter the data json when i click in a button, example, in the Navbar i have:我有一个 json 文件作为服务器,当我单击一个按钮时,我需要过滤数据 json,例如,在导航栏中我有:

const NavBar = ({setSearchValue, setType}) => {
  const handleType = (heroType) =>{
    setType(heroType)
    }

  return (
// this input is ok, i can search data from here
              <input id='searchInput' placeholder='Search' onChange={(event) => {setSearchValue(event.target.value)}}/>
//these are the buttons
            <Nav.Link onClick={() => handleType('All')}>All Heroes</Nav.Link>
            <Nav.Link onClick={() => handleType('Flying')} >Flying Heroes</Nav.Link>
            <Nav.Link onClick={() => handleType('Flightless')}>Flightless Heroes</Nav.Link>

and this is where i need to show it这就是我需要展示的地方

  //import Navbar
        import NavBar from "./NavBar";
        
        const Home = () => {
    // saved the data i need to show 
          const [content, setContent] = useState();
    // saved the searchvalue of navbar, its ok.
          const [searchValue, setSearchValue] = useState("");
    // i tried save the button data here, next with a IF function i tried to show it, no work
          const [type, setType] = useState("Flying");
        
          useEffect(() => {
// get json dta
            const getData = async () => {
              const response = await db.get("data");
        
              let data = response.data.filter((val) => {
// if no searchValue, return all
                if (searchValue === "") return val;
//if searchVale, return coincidences
                else if (val.nombre.toLowerCase().includes(searchValue.toLowerCase()))
                  return val;
              });
        // returns bootstrap rows depending on number of elements
              const rows = [...Array(Math.ceil(data.length / 3))];
              const imagesRows = rows.map((row, idx) =>
                data.slice(idx * 3, idx * 3 + 3)
              );
        //saved all in setContent
              setContent(
                //code
                )
            getData();
          }, [searchValue]);
        
          return (
            <>

              <NavBar setSearchValue={setSearchValue} setType={setType} />
//show content
              <Container>{content >= 0 ? <p>No results</p> : content}</Container>
            </>
          );
        };

I've tried a lot of things, i think i need change a lot of code ia want this work.我已经尝试了很多东西,我想我需要更改很多代码我想要这项工作。 Any help would be extremely appreciated.任何帮助将不胜感激。

EDIT Json:编辑Json:

        {
          "data": [
            {
              "id": 0,
              "nombre": "Punisher",
              "puedeVolar": false,
              "nombreReal": "Frank Castle",
              "avatarURL": ""
            },
            {
              "id": 1,
              "nombre": "Green Arrow",
              "puedeVolar": false,
              "nombreReal": "Oliver Jonas Queen",
              "avatarURL": ""
            },
            {
              "id": 2,
              "nombre": "Human Torch",
              "puedeVolar": true,
              "nombreReal": "Jonathan Lowell Spencer",
              "avatarURL": ""
            },
            {
              "id": 3,
              "nombre": "Martian Manhunter",
              "puedeVolar": true,
              "nombreReal": "J'onn J'onzz",
              "avatarURL": ""
            },
            {
              "id": 4,
              "nombre": "Aquaman",
              "puedeVolar": false,
              "nombreReal": "Arthur Curry",
              "avatarURL": ""
            }
}

So when clicked button display heroes.puedeVolar === false or display heroes.puedeVolar === true, depending of the button clicked所以当点击按钮时显示 heros.puedeVolar === false 或显示 heros.puedeVolar === true,取决于点击的按钮

Post your JSON to help you.发布您的 JSON 以帮助您。 You're lifting up correctly the states, you just need to do the same that you did with the input.您正确地提升了状态,您只需要执行与输入相同的操作。 Put the type as a dependecie of useEffect and inside it filter your JSON with your type value.将类型作为 useEffect 的依赖项,并在其中使用您的类型值过滤您的 JSON。

 useEffect(()=>{ //... Keep your working code let data = response.data.filter((val) => { //Keep your working code or refactor it //Add you new filter params if (val.type === type) return val; } }, [type, searchValue]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM