简体   繁体   English

循环遍历数组并选择特定于 setstate

[英]loop through an array and choose specific to setstate

New react developer here, here i have two API's, first one gives an object:新的反应开发人员在这里,我有两个 API,第一个给出 object:

{ id: "98s7faf", isAdmin: true, name: "james"}

second one gives an array of objects:第二个给出了一个对象数组:

[
  { billingName: "trump", driverName: "james" },
  { billingName: "putin", driverName: "alex" },
  { billingName: "kalle", driverName: "james" },
  { billingName: "sussu", driverName: "trump" },
  { billingName: "vladimir", driverName: "james" },
]

my question is, when user goes to the page, the page should automatically check both API'S, from first api name and from second api driverName , and if those two have same value then take that specific object from an array and pass it to these:我的问题是,当用户转到该页面时,该页面应自动检查两个 API,从第一个 api name和第二个 api driverName ,如果这两个具有相同的值,则从数组中获取特定的 ZA8CFDE6331BD59EB66AC96F8911

setOrders(res);
setRenderedData(res);

so at the moment there are three objects (those which have value of james ) inside an array which matches name from first api, so it should pass those, and the rest which have different value it should not let them pass.所以目前在一个数组中有三个对象(那些具有james的值)与第一个 api 的name匹配,因此它应该通过这些对象,而具有不同值的 rest 不应该让它们通过。 here is my code, what have i done wrong?这是我的代码,我做错了什么? instead of some(({ driverName }) i need some kind of filter?而不是some(({ driverName })我需要某种过滤器?

 useEffect(() => { api.userApi.apiUserGet().then((res1?: User ) => { return api.caApi.apiCaGet(request).then((res?: CaDto[]) => { if (res.some(({ driverName }) => driverName === res1?.name)) { setOrders(res); setRenderedData(res); console.log(res); } }); }); }, [api.caApi, api.userApi]);

you need to filter your response to extract the right objects given your condition.您需要根据您的条件过滤您的响应以提取正确的对象。

 useEffect(() => {
  api.userApi.apiUserGet().then((res1?: User ) => {
  return api.caApi.apiCaGet(request).then((res?: CaDto[]) 
  => {
    const filteredData = res?.filter(({ driverName }) => driverName === res1?.name);
    if(filteredData?.length) {
      setOrders(filteredData);
      setRenderedData(filteredData);
      console.log(filteredData);
    }
  });
});
}, [api.caApi, api.userApi]);

note: having 2 states that holds the same values (orders, renderedData) is not a good practice, you might consider to refactor your logic.注意:拥有两个具有相同值的状态(订单、渲染数据)不是一个好习惯,您可能会考虑重构您的逻辑。

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

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