简体   繁体   English

如何使用 React 下拉列表中的选定值作为 api url id?

[英]How to use selected value in React dropdown as api url id?

I want to render into table specific data from url with id taken after user select the needed value so here is my code: fetching data for select options:我想在用户选择所需值后使用 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);
  };

now fetching data in dashboard function for selected 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,
    ]);
  };

now render data in return:现在渲染数据作为回报:

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

but nothing appear after select the value needed how can i fix it and does react allow to use selected value like this?但是在选择所需的值后什么也没有出现,我该如何修复它,并且反应是否允许使用这样的选定值?

data数据

[
  {
    "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"
    }
  },

So based on the conversation in the comment section the value is there in selected .因此,根据评论部分中的对话,值在selected Then the only problem is useEffect is not triggered on change because of empty dependency array.那么唯一的问题是useEffect由于空依赖数组而不会在更改时触发。

I suggest few modifications in your code:我建议对您的代码进行一些修改:

  1. Add to the dependency array selected as [selected] which will trigger the function once you have change on that state.添加到selected[selected]的依赖项数组,一旦您更改了该状态,它将触发该功能。
  2. Check for null or undefined values in order not to concatenate without value.检查nullundefined值,以免在没有值的情况下进行连接。
  3. Also I added one extra slash into your URL after users so now it's users/ .此外,我在users之后在您的 URL 中添加了一个额外的斜杠,所以现在是users/
  4. So the URL would be at the end of the day:所以 URL 将在一天结束时:
`https://jsonplaceholder.typicode.com/users/${selected}`

Based on the explanation try as:根据解释尝试如下:

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 suggestion: +1 建议:

Maybe it's not related but you have in .map() an extra [] which might be not needed, so try as:也许它不相关,但您在.map()一个可能不需要的额外[] ,因此请尝试:

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

In this way .map() will return an array of objects with the properties of id , name , username .这样.map()将返回一个对象数组,其属性为idnameusername

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

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