react.js中过滤数据时的过滤问题

问题描述 投票:0回答:1

我正在使用 React 和 Firebase 实时数据库制作一个基本的笔记应用程序。我在过滤过程中遇到问题。

这是代码:

import { useState } from 'react';
import classes from './NavBar.module.css';

export default function NavBar(props) {
  const [filterSearch, setFilterSearch] = useState('');

  let filterNote = [];
  const filterHandler = (event) => {
    setFilterSearch(event.target.value.toLowerCase().trim());

    filterNote = props.notesData.filter((note) => {
      console.log(filterSearch, ' and ', note.title);
      return note.title.toLowerCase().trim() === filterSearch;
    });
    console.log(filterNote);

    // props.setNoteData(filterNote);
  };

  return (
    <div className='container'>
      <nav>
        <div className={classes['nav-heading']}>
          <h1>Notes</h1>
        </div>
        <div className={classes['nav-search']}>
          <div className={classes['nav-controls']}>
            <input type='text' name='search' id='search' placeholder='Search for Title' onChange={filterHandler} />
          </div>
        </div>
      </nav>
    </div>
  );
}

数据来自App.js:

import './App.css';
import NavBar from './components/Navbar/NavBar';
import Header from './components/Header/Header';
import Card from './components/Card/Card';
import { useEffect, useState } from 'react';

function App() {
  const [notedata, setNoteData] = useState([]);

  // fetch data from firebase.
  let autoFetch = async () => {
    const response = await fetch('https://notes-keeper-react-default-rtdb.firebaseio.com/notes.json');
    const data = await response.json();

    let notesArr = [];
    Object.keys(data).map((key) => {
      notesArr.push(data[key]);
    });
    setNoteData(notesArr);
  };

  useEffect(() => {
    autoFetch();
  }, []);

  console.log(notedata);
  return (
    <div className='App'>
      <NavBar notesData={notedata} setNoteData={setNoteData} />
      <Header autoFetch={autoFetch} />
      <Card notes={notedata} />
    </div>
  );
}

export default App;

当我取消注释时,在filterHandler函数上props.setNoteData(filterNote);我的所有卡片从UI中消失。

我想要什么


我希望,对于每个 onChange 事件执行过滤并将过滤后的数据显示到 UI。

javascript reactjs react-hooks state react-props
1个回答
0
投票

使

<NavBar/>
组件成为 受控组件,它有两个 props:
value
onChange(value)

NavBar.js

export default function NavBar(props) {
    return (
        <div className="container">
            <nav>
                <div>
                    <h1>Notes</h1>
                </div>
                <div>
                    <div>
                        <input
                            type="text"
                            name="search"
                            id="search"
                            placeholder="Search for Title"
                            value={props.value}
                            onChange={(event) => props.onChange(event.target.value)}
                        />
                    </div>
                </div>
            </nav>
        </div>
    );
}

filterSearch
组件中声明
<App/>
状态,将其传递给
<NarBar/>
组件,当用户在输入中键入内容时,通过
notedata
状态过滤
filterSearch
。否则,使用从远程服务器获取的初始数据。

App.js

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

export default function App() {
    const [notedata, setNoteData] = useState([]);
    const [filterSearch, setFilterSearch] = useState("");

    let autoFetch = async () => {
        const response = await fetch("https://notes-keeper-react-default-rtdb.firebaseio.com/notes.json");
        const data = await response.json();
        let notesArr = [];
        Object.keys(data).map((key) => {
            notesArr.push(data[key]);
        });
        setNoteData(notesArr);
    };

    useEffect(() => {
        autoFetch();
    }, []);

    const filterNote = filterSearch
        ? notedata.filter((note) => note.title.toLowerCase().trim() === filterSearch.toLowerCase().trim())
        : notedata;

    return (
        <div className="App">
            <NavBar value={filterSearch} onChange={(value) => setFilterSearch(value)} />
            <ul>
                {filterNote.map((note, idx) => (
                    <li key={idx}>
                        <h2>{note.title}</h2>
                        <p>{note.note}</p>
                    </li>
                ))}
            </ul>
        </div>
    );
}

代码沙盒

© www.soinside.com 2019 - 2024. All rights reserved.