首页 > 解决方案 > 如何使用 React 下拉列表中的选定值作为 api url id?

问题描述

我想在用户选择所需的值后使用 id 将 url 中的特定数据呈现到表中,所以这是我的代码:为选择选项获取数据:

export default function Dashboard() {
  
const [value, setValue] = useState();
  const [students, setstudents] = useState([]);
  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const resp = await Axios({
          method: "GET",
          url: "https://jsonplaceholder.typicode.com/users",
          headers: {
            "Content-Type": "application/json",
          },
        });
        setstudents(resp.data);
      } catch (err) {}
    };
    fetchStudents();
  }, []);
  
  const classes = useStyles();
  const [selected,setselected]=useState();
  
  const options = students.map(s => ({
    "value" : s.id,
    "label" : s.username
  }))
  const handleChange = (event) => {
    setselected(event.value);
  };

现在在仪表板功能中获取选定值的数据:

const [tabl, settabl] = useState([]);
  useEffect(() => {
    const fetchtabl = async () => {
      try {
        const resp = await Axios({
          method: "GET",
          url: "https://jsonplaceholder.typicode.com/users"+{selected},
          headers: {
            "Content-Type": "application/json",
          },
        });
        settabl(resp.data.surveys);

      } catch (err) {
        console.log(err);
      }
    };
    fetchtabl();
  }, []);
  const getTableData = (tabl) => {
    return tabl.map((tab) => [
      tab.id,
      tab.name,
      tab.username,
    ]);
  };

现在渲染数据作为回报:

 Select the course:
          <Select options={options} onChange={handleChange}/>
  <Table
              tableHead={["Course Code", "Course Name", "Survey Link"]}
              tableData={getTableData(tabl)}
              tableHeaderColor="primary"
            />

但是在选择所需的值后什么都没有出现我该如何修复它并且反应是否允许使用这样的选定值?

数据

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "email": "Nathan@yesenia.net",
    "address": {
      "street": "Douglas Extension",
      "suite": "Suite 847",
      "city": "McKenziehaven",
      "zipcode": "59590-4157",
      "geo": {
        "lat": "-68.6102",
        "lng": "-47.0653"
      }
    },
    "phone": "1-463-123-4447",
    "website": "ramiro.info",
    "company": {
      "name": "Romaguera-Jacobson",
      "catchPhrase": "Face to face bifurcated interface",
      "bs": "e-enable strategic applications"
    }
  },

标签: javascriptreactjsselectfrontend

解决方案


因此,根据评论部分中的对话,该值存在于selected. 那么唯一的问题是useEffect不会因为空的依赖数组而触发更改。

我建议对您的代码进行一些修改:

  1. 添加到依赖数组selected,因为[selected]一旦你改变了那个状态,它就会触发函数。
  2. 检查nullorundefined值,以免在没有值的情况下连接。
  3. 我还在你的 URL 中添加了一个额外的斜杠,users所以现在它是users/.
  4. 所以 URL 将在一天结束时:
`https://jsonplaceholder.typicode.com/users/${selected}`

根据解释尝试:

useEffect(() => {
    const fetchtabl = async () => {
      try {
        const resp = await Axios({
          method: "GET",
          url: `https://jsonplaceholder.typicode.com/users/${selected}`,
          headers: {
            "Content-Type": "application/json",
          },
        });
        settabl(resp.data.surveys);

      } catch (err) {
        console.log(err);
      }
    };

    if (selected) {
       fetchtabl();
    }
}, [selected]);

+1 建议:

也许它不相关,但您有一个可能不需要.map()的额外内容,因此请尝试:[]

const getTableData = (tabl) => {
    return tabl.map((tab) => ({
      tab.id,
      tab.name,
      tab.username,
    }));
};

这样将返回一个具有, ,.map()属性的对象数组。idnameusername


推荐阅读