簡體   English   中英

在 React 中,如何將選定的下拉數據傳遞給 state

[英]In React, How to pass the selected dropdown data to state

我一直在嘗試為我的項目制作一個多選下拉列表,一個人可以在其中 select 他們在網站注冊時教授哪些學校科目。 但是我在將所選值傳遞給簡單選項下拉列表中聲明的 state 方面遇到了麻煩。

When I try to make the POST request to my API (made with NodeJS, express and mongoDB for database), the console.log returns that the subject object has three arrays with all the subject data. 我只想傳遞 _id 字段,因為它是所要求的。

當我的 API GET 請求返回所有字段時,我應該如何僅獲取主題 _id?

參考代碼:

API 調用

async function listActiveSubjects() {
    const response = await api.get("/subject");
    return response.data;
}

請求返回的 JSON:

{
  "subjects": [
     {
            "isActive": true,
            "_id": "6001e71606a211004877f6e1",
            "name": "Subject 1",
            "description": "Subject 1 description",
            "__v": 0
      },
      {
            "isActive": true,
            "_id": "6001e71606a211004877f6e1",
            "name": "Subject 2",
            "description": "Subject 2 description",
            "__v": 0
      },
  ]
}

反應功能組件:

import React, { useState, useEffect } from 'react';

import { listActiveSubjects } from '../../../../services/subjects';

const TeacherClassInfo = props => {
    const [subjects, setSubjects] = useState();
    const [selected, setSelected] = useState({ _id: ''})

    const handleListActiveSubjects = async () => {
        const getSubjects = await listActiveSubjects();
        setSubjects(getSubjects);
    }

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

    const onChange = (key, _id) => {
        setSelected(() => ({
            [key]: _id,
        }))
    }

    return(
        <select>
          {subjects &&
            subjects.subjects.map((subjects) => {
              return (
                <option
                  onChange={_id => onChange(_id)}
                    key={subjects._id}
                    value={selected[subjects._id]}>
                      {subjects.name}
                 </option>
              );
           })
         }
      </select>  
    );

日志顯示的output為:

subjects: Array(2)
    0: {isActive: true, _id: "6001e71606a211004877f6e1", name: "Subject 1", description: "Subject 1 
description", __v: 0}
    1: {isActive: true, _id: "6001e73106a211004877f6e2", name: "Subject 2", description: "Subject 2 description", __v: 0}
length: 2

在我的理解中應該是:

subjects: Array(1)
    0: {_id: "6001e71606a211004877f6e1"}
length: 1

,就像在數據庫上配置的那樣。

從我在這里看到的其他教程和問題中,這應該設置選定的 id,但不幸的是它沒有按預期工作。 任何幫助將非常感激

您可以使用response.data.subjects數組上的map()方法返回數組中的所有_id值。 這將遍歷每個主題,並根據回調中返回的值創建一個新數組。 在這種情況下,它是_id屬性值。

async function listActiveSubjects() {
  const response = await api.get("/subject");
  const ids = response.data.subjects.map(({ _id }) => _id);
  return ids;
}

這將導致:

[
  "6001e71606a211004877f6e1",
  "6001e73106a211004877f6e2",
]

只給你你需要的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM