按 id 过滤数组对象 - REACT

发布于 2025-01-15 03:21:58 字数 3499 浏览 2 评论 0原文

我在 React 中通过 ID 过滤对象数组中的一个对象时遇到了很大的困难。让我解释一下:

该应用程序是一个笔记应用程序,它存储您创建的每条笔记及其标题、文本(名称)和创建日期。关键是身份证。

现在,我尝试在每次单击注释时创建一个弹出模式,我设法做得很好,除了一件事:当模式出现时,它不仅显示所选注释,还显示所有注释列表。我尝试过使用不同的数组方法来过滤我需要的注释,但没有成功。

这是 App.js 文件:

import React, { useState } from 'react';
import './App.css';
import Form from './components/Form';
import List from './components/List';
import { v4 as uuidv4 } from 'uuid';
import Modal from 'react-modal';
import ModalList from './components/ModalList';


Modal.setAppElement('#root');

function App() {
  /*HOOKS */

  const [list, setList] = useState([]);
  const [modalList, setModalList] = useState([]);


  //for modal:
  let subtitle;
  const [modalIsOpen, setIsOpen] = React.useState(false);




  /*FUNCTIONS */

  //add new notes
  function handleAdd(title, name) {
    if (name) {
      const newList = list.concat({ title: title, name: name, id: uuidv4(), date: getCurrentDate() });
      setList(newList);
      console.log(newList);
      const newModalList = list.concat({ title: title, name: name, id: uuidv4(), date: getCurrentDate() });
      setModalList(newModalList);
    }
    else { alert("You should complete the notes field") }

  }


  //get the date for adding the note
  function getCurrentDate() {

    let newDate = new Date()
    let date = newDate.getDate();
    let month = newDate.getMonth() + 1;
    let year = newDate.getFullYear();
    let hours = newDate.getHours();
    let minutes = newDate.getMinutes();

    return `${month < 10 ? `0${month}` : `${month}`}/${date}/${year}, ${hours}:${minutes < 10 ? `0${minutes}` : `${minutes}`} hs.`

  }


  //deleting a note
  function del(x) {
    if (window.confirm("Do you really want to delete this item? The action is permanent.")) {
      const newList = list.filter((item) => item.id !== x);
      setList(newList);
    }
  }



  //opening a modal
  function openModal() {

    setIsOpen(true);
  }

  //after opening a modal
  function afterOpenModal() {
    // references are now sync'd and can be accessed.
    subtitle.style.color = '#f00';

  }

  //closing a modal
  function closeModal() {
    setIsOpen(false);

  }


  /*APP */
  return (
    <>

      <div>
        {/* MODAL */}
        <Modal
          isOpen={modalIsOpen}
          onAfterOpen={afterOpenModal}
          onRequestClose={closeModal}
          style={customStyles}
          contentLabel="Example Modal"
        >
          {modalList.map((item) => { return <ModalList key={item.id} item={item} quit={closeModal} /> })}
        </Modal>
      </div>

      {/* FORM */}


      <div className='App'>
        <Form handleNew={handleAdd} />
      </div>

      {/* NOTES LIST */}
      <div className='notes-list'>
        {list.map((item) => { return <List key={item.id} item={item} quit={del} addModal={openModal} /> })}
      </div>

    </>
  );
}

export default App;



这是 ModalList.jsx 文件:

const ModalList = (props) => {
    const { item, quit} = props;

    /*LIST */
    return (
        <li ><button className='delete' onClick={()=>quit(item.id)}>x</button><p className='note-title'>{item.title}</p><p>{item.date}</p><p className='note-name'>{item.name}</p> </li>


    );
}
 
export default ModalList;

我知道我必须以某种方式按 ID 过滤对象,以便只显示我单击的内容,而不是列表中的所有现有元素,但我找不到路。

多谢!

I'm having a big struggle with filtering an object of an array of objects by its ID in React. Let me explain:

The App is a Notes app, that stores every note you create with its Title, Text(name) and created date. The key is the ID.

Now I'm trying to create a popup modal every time I click on a note, which I managed to do ok, except for one thing: when the modal appears, it doesn't show only the selected note but all the notes list. I've tried with different array methods to filter the note I need, but didn't succeed.

This is the App.js file:

import React, { useState } from 'react';
import './App.css';
import Form from './components/Form';
import List from './components/List';
import { v4 as uuidv4 } from 'uuid';
import Modal from 'react-modal';
import ModalList from './components/ModalList';


Modal.setAppElement('#root');

function App() {
  /*HOOKS */

  const [list, setList] = useState([]);
  const [modalList, setModalList] = useState([]);


  //for modal:
  let subtitle;
  const [modalIsOpen, setIsOpen] = React.useState(false);




  /*FUNCTIONS */

  //add new notes
  function handleAdd(title, name) {
    if (name) {
      const newList = list.concat({ title: title, name: name, id: uuidv4(), date: getCurrentDate() });
      setList(newList);
      console.log(newList);
      const newModalList = list.concat({ title: title, name: name, id: uuidv4(), date: getCurrentDate() });
      setModalList(newModalList);
    }
    else { alert("You should complete the notes field") }

  }


  //get the date for adding the note
  function getCurrentDate() {

    let newDate = new Date()
    let date = newDate.getDate();
    let month = newDate.getMonth() + 1;
    let year = newDate.getFullYear();
    let hours = newDate.getHours();
    let minutes = newDate.getMinutes();

    return `${month < 10 ? `0${month}` : `${month}`}/${date}/${year}, ${hours}:${minutes < 10 ? `0${minutes}` : `${minutes}`} hs.`

  }


  //deleting a note
  function del(x) {
    if (window.confirm("Do you really want to delete this item? The action is permanent.")) {
      const newList = list.filter((item) => item.id !== x);
      setList(newList);
    }
  }



  //opening a modal
  function openModal() {

    setIsOpen(true);
  }

  //after opening a modal
  function afterOpenModal() {
    // references are now sync'd and can be accessed.
    subtitle.style.color = '#f00';

  }

  //closing a modal
  function closeModal() {
    setIsOpen(false);

  }


  /*APP */
  return (
    <>

      <div>
        {/* MODAL */}
        <Modal
          isOpen={modalIsOpen}
          onAfterOpen={afterOpenModal}
          onRequestClose={closeModal}
          style={customStyles}
          contentLabel="Example Modal"
        >
          {modalList.map((item) => { return <ModalList key={item.id} item={item} quit={closeModal} /> })}
        </Modal>
      </div>

      {/* FORM */}


      <div className='App'>
        <Form handleNew={handleAdd} />
      </div>

      {/* NOTES LIST */}
      <div className='notes-list'>
        {list.map((item) => { return <List key={item.id} item={item} quit={del} addModal={openModal} /> })}
      </div>

    </>
  );
}

export default App;



And this is the ModalList.jsx file:

const ModalList = (props) => {
    const { item, quit} = props;

    /*LIST */
    return (
        <li ><button className='delete' onClick={()=>quit(item.id)}>x</button><p className='note-title'>{item.title}</p><p>{item.date}</p><p className='note-name'>{item.name}</p> </li>


    );
}
 
export default ModalList;

I know I have to someway filter the object by its ID so that only appears what I clicked and not all the existing elements in the list, but I'm not finding the way.

Thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九八野马 2025-01-22 03:21:58

您在这里使用 Array.map 执行它应该执行的操作(列出项目),而不是您应该使用 Array.filter 它将返回您需要的 ModalItem

You are using Array.map here which is doing what it's supposed to do (listing the items), instead you should be using Array.filter which would return the ModalItem you need

初见 2025-01-22 03:21:58
{list.map((item) => { return <List key={item.id} item={item} quit={del} addModal={openModal} /> })}

openModal 需要将您单击的项目作为参数传递给回调。

类似于:

{list.map((item) => { return <List key={item.id} item={item} quit={del} addModal={() => openModal(item)} /> })}

然后 openModal 函数需要将该参数传递给 Modal 组件。为了实现这一点,您可以将其存储在 modalList 中,例如通过 setModalList([item])

{list.map((item) => { return <List key={item.id} item={item} quit={del} addModal={openModal} /> })}

openModal needs pass the item you clicked as a parameter and pass it to the callback.

Something like:

{list.map((item) => { return <List key={item.id} item={item} quit={del} addModal={() => openModal(item)} /> })}

Then openModal function needs to pass that parameter to the Modal component. To achieve that you can store it in your modalList for instance via setModalList([item])

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文