简体   繁体   English

如何从 map 中的 promise 设置 JS 变量?

[英]How do I set JS variable from promise within map?

I'm working on Ionic 4 and React and I'm trying to get data from a function to return into the page, but i'm not able to get the data out of the promise.我正在研究 Ionic 4 和 React,我正在尝试从 function 获取数据以返回页面,但我无法从 promise 中获取数据。

FYI, i'm using the functional version/pattern of react.仅供参考,我正在使用反应的功能版本/模式。

participants.map(participant => {

    var paymentStatus = false;
    fetchSelectedPaymentEvents(participant, selectedEvent)
      .then(data => { 
        paymentStatus = data;
      })

    return (
        <IonButton color={paymentStatus}>Button<IonButton>
    );

});

I've tried using UseState which works somewhat, but I need it to work within the map, but I can't use useState within a React Hook.我尝试过使用 UseState,它有点用,但我需要它在 map 中工作,但我不能在 React Hook 中使用 useState。

Edit: I've tried async/await, but I get the following error when I do: Error: Objects are not valid as a React child (found: [object Promise]).编辑:我尝试过异步/等待,但是当我这样做时出现以下错误:错误:对象作为 React 子级无效(找到:[object Promise])。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

Edit:编辑:

Here's the code for fetchSelectedPaymentEvents():这是 fetchSelectedPaymentEvents() 的代码:

function fetchSelectedPaymentEvents(participant_id: any, event_id: any) {

        return axios({
            url: "URL",
            method: "POST",
            data: {
                "participant_id": participant_id,
                "payment_event_id": event_id
            }
        }).then(response => {
            var data = response.data["payment_records"]

            if (data === undefined || data.length == 0) {
                return "danger"
            }

            return "success"
        })

    }

Btw, the purpose of returning "danger" or "success" is not to print exactly the text, but more to be used for styling an Ionic element.顺便说一句,返回“危险”或“成功”的目的不是准确地打印文本,而是更多地用于设置 Ionic 元素的样式。 Apologies if my code is too misleading.如果我的代码误导性太强,我们深表歉意。 I've edited to make it closer to what I actually need.我进行了编辑以使其更接近我实际需要的内容。

I also think your overall structure of your component is very error prone.我还认为您的组件的整体结构非常容易出错。 Here is how i would attempt to do what you intend to do:以下是我将如何尝试做你打算做的事情:

const Component = () => {
  const participants = // whereever you get participants from;
  return (
    <ul>
      {participants.map(participant => {
          return <Participant participant={participant} />
        })
      }
    </ul>
  )
}

const Participant = ({ participant }) => {
  const [paymentStatus, setPaymentStatus] = useState("//initialState?");

  useEffect(() => {
    fetchSelectedPaymentEvents(participant, selectedEvent) // dont where selectedEvent comes from?
      .then(data => { 
        setPaymentStatus(data);
      })
  }, [participant]}

  return (
    <li>
      {paymentStatus}
    </li>
  )
}

Hope this makes it a little easier to structure your component希望这可以使您的组件更容易构建

when you call a Promise like fetchSelectedPaymentEvents and use the.then syntax, you are running fetchSelectedPaymentEvents synchronously instead of asynchronously.当您调用 Promise 之类的 fetchSelectedPaymentEvents 并使用 .then 语法时,您正在同步运行 fetchSelectedPaymentEvents 而不是异步运行。 Therefore your return statement gets called before the.then.因此,您的 return 语句在 the.then 之前被调用。

YOu have to use the async await syntax to solve thi issue:你必须使用异步等待语法来解决这个问题:

participants.map(async participant => {
    const paymentStatus = await fetchSelectedPaymentEvents(participant, selectedEvent);

    return (
        <IonText>{paymentStatus}<IonText>
    );
});
Promise.all(participants.map(participant => {

    var paymentStatus = false;
    fetchSelectedPaymentEvents(participant, selectedEvent)
      .then(data => { 
        paymentStatus = data;
      })

    return (
        <IonText>{paymentStatus}<IonText>
    );

}));

try wrapping up your map function with promise.all() as you function as a parameter to this尝试将 map function 与promise.all()作为 ZC1C425268E68385D1AB54 的参数

Here is an approach that works, it looks a little different than yours, since i did it my way, but i hope this can help.这是一种可行的方法,它看起来与您的方法有些不同,因为我是按照自己的方式进行的,但我希望这会有所帮助。 Its confusing when using promises and pass them down and to figure out where and when to async and await, esspecially with React hooks.使用 Promise 并将它们传递下去并弄清楚何时何地进行异步和等待时会令人困惑,尤其是使用 React 钩子时。 I recommend using the hooks for your state logic and flow as much as you can otherwise you your code can get error prone very easily.我建议为您的 state 逻辑和流程尽可能多地使用钩子,否则您的代码很容易出错。

const fetchSelectedPaymentEvents = async (participant_id, event_id) => {
  try {
    const response = await axios({
      url: "URL",
      method: "POST",
      data: {
        participant_id: participant_id,
        payment_event_id: event_id
      }
    });
    var data = response.data["payment_records"];
    if (data === undefined || data.length == 0) {
      return "danger";
    }
    return "success";
  } catch (error) {
    return "failed";
  }
};

const App = () => {
  const [status, setStatus] = useState("pending");

  useEffect(() => {
    fetchSelectedPaymentEvents().then(data => setStatus(data));
  }, []);

  return <div className="App">{status}</div>;
};

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

相关问题 如何设置对变量的Promise响应 - How do i set the response of a promise to a variable 如何将 Angular JS 服务中的变量设置为来自 AngularJS 服务中 $http 调用的响应数据? - How do I set a variable within an Angular JS service to the response data from an $http call within an AngularJS service? 如何将诺言的结果返回给地图函数 - How do I return the result from promise to map function 如何在 Postman 中从数组中设置环境变量? - How do I set an Enviromental Variable in Postman, from an array, within an array? 如何从setTimeout中获取另一个作用域中的变量集? - How do I get a variable set in another scope from within a setTimeout? 如何在Promise JS中将Promise数组转换为每个Promise解析的值的数组? - How do I convert an Array of Promise to an Array of the values resolved from each Promise in vanilla JS? 我如何通过 React JS 中的变量 map - How do I map through a variable in React JS 如何在 Handlebars.js 块中使用和设置自定义变量? - how do I use and set custom variables from within a Handlebars.js block? 如何在Node.js中重新发送承诺? - How do I res.send within a promise in node.js? 如何在js脚本中读取docker环境变量? - How do I read a docker environment variable within a js script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM