首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将承诺分配给反应中的变量

问将承诺分配给反应中的变量
EN

Stack Overflow用户
提问于 2020-08-18 16:57:04
回答 3查看 3.5K关注 0票数 0

总的来说,我对JavaScript/React非常陌生,并且很难理解Promise和async的概念。

首先,我有getSimById,JS文件中的API调用,它返回一个Promise

代码语言:javascript
复制
export function getSimById(simId) {
  return fetch(simsUrl + "/results/" + simId, {
    method: "GET",
    headers: new Headers({
      Authorization: "Basic " + base64.encode(login + ":" + password)
    })
  })
    .then(handleResponse)
    .catch(handleError);
}

handleResponse是一个异步函数。

代码语言:javascript
复制
export async function handleResponse(response) {
  if (response.ok) {
    let someResponse = response.json();
    return someResponse;
  }

  if (response.status === 400) {
    throw new Error(error);
  }

  const error = await response.text();
  throw new Error("Network response was not ok.");
}

现在我有了一个函数组件,它返回一个Table

代码语言:javascript
复制
import React, { useState, useEffect } from "react";
import { getSimById } from "../api/outrightSimulatorApi";

function SimulationReport(props) {

  const location = useLocation();
  const [simResult, setSimResult] = useState([]);

  useEffect(() => {
    getSimById(location.state.simId).then(result => setSimResult(result));
  }, []);

  let reformattedData = getSimById(location.state.simId).then(
    data => reformattedData = data?.markets?.length ? data.markets.reduce(
      (accumulator, market) =>
        market.selections.map(({ name, probability }, index) => ({
          ...accumulator[index],
          "Team name": name,
          [market.name]: probability,
        })),
      [],
    ) : null);

  return (
      <div>
          <Table striped bordered hover size="sm" responsive>
            <thead>
              <tr>{

              }
              </tr>
            </thead>
            <tbody>{

             }
            </tbody>
          </Table>
      </div>
  );

在这段代码中,我希望通过reformattedData映射为一个数组,并最终通过返回的Table中的值进行映射。但是,reformattedData在这个实例中不是一个数组,实际上是一个Promise。因此,每当我尝试访问类似reformattedData[0]的东西时,它实际上都会返回undefined,并且我无法在Table中映射它的值。在这种情况下,我如何将承诺赋值给一个变量,以便对其执行操作?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-08-18 17:07:28

您不应该在两个不同的地方调用getSimById,它只应该在useEffect回调中,它应该将location.state.simId作为一个依赖项列出。

类似于这样的东西:

代码语言:javascript
复制
function SimulationReport(props) {

  const location = useLocation();
  const [simResult, setSimResult] = useState([]);

  useEffect(() => {
    getSimById(location.state.simId).then(data => {
        const reformattedData = data?.markets?.length ? data.markets.reduce(
          (accumulator, market) =>
            market.selections.map(({ name, probability }, index) => ({
              ...accumulator[index],
              "Team name": name,
              [market.name]: probability,
            })),
          [],
        ) : null;
        setSimResult(reformattedData); // *** Set state here
      })
      .catch(error => {
        // *** Handle/report error
      });
  }, [location.state.simId]); // *** Note the dependency

  return (
      <div>
          <Table striped bordered hover size="sm" responsive>
            <thead>
              <tr>{

              }
              </tr>
            </thead>
            <tbody>{
              // *** Use `simResult` when rendering
              simResult.map(entry => <markup>for entry</markup)
             }
            </tbody>
          </Table>
      </div>
  );
}

还有另一个问题:如果效果在到达之前再次运行,您希望忽略异步获得的结果。为此,您可以从useEffect回调中返回一个函数,以便React可以在发生时告诉您,如下所示:

代码语言:javascript
复制
  useEffect(() => {
    let cancelled = false; // ***
    getSimById(location.state.simId).then(data => {
        if (cancelled) {
            // Don't use it
            return;
        }
        const reformattedData = data?.markets?.length ? data.markets.reduce(
          (accumulator, market) =>
            market.selections.map(({ name, probability }, index) => ({
              ...accumulator[index],
              "Team name": name,
              [market.name]: probability,
            })),
          [],
        ) : null;
        setSimResult(reformattedData);
      })
      .catch(error => {
        // Handle/report error
      });
      return () => {        // *** A callback React will use when the effect runs again
        cancelled = true;   // *** Remember that *this* call has been cancelled
      };
  }, [location.state.simId]);

Dan的这篇文章提供了一些关于钩子的优秀信息,尤其是useEffect。

票数 1
EN

Stack Overflow用户

发布于 2020-08-18 17:10:17

好的,所以您的api调用与expect一样工作,您将在

代码语言:javascript
复制
useEffect(() => {
    getSimById(location.state.simId).then(result => setSimResult(result));
  }, []);

它可以像解析数据一样同时简化。

代码语言:javascript
复制
getSimById(location.state.simId).then(parseSimResult);

但你的问题是let在这里。

一个可能的解决办法可以是:

退出组件(可能是实用程序)?

代码语言:javascript
复制
export const parseSimResults = (simResults) => {
  return simResults.markets.reduce(
      (accumulator, market) =>
        market.selections.map(({ name, probability }, index) => ({
          ...accumulator[index],
          "Team name": name,
          [market.name]: probability,
        })),
      [],
    )
}; 

然后仅在呈现映射中将simResults抛到组件呈现中。

代码语言:javascript
复制
<thead>
  {simResult && simResults.map(r => {
    <tr key="someKEY">
         {
          ...
         }
    </tr>
  })}
</thead>

生成完整代码

代码语言:javascript
复制
const parseSimResults = (simResults) => {
  return simResults.markets.reduce(
      (accumulator, market) =>
        market.selections.map(({ name, probability }, index) => ({
          ...accumulator[index],
          "Team name": name,
          [market.name]: probability,
        })),
      [],
    )
}; 

const MyComponent.... {
  const [simResults, setSimResults] = useState([]);

  useEffect(() => {
    getSimById(location.state.simId).then(parseSimResults);
  }, []);

  return simResults.map(r => <your JSX>)
}
票数 1
EN

Stack Overflow用户

发布于 2020-08-18 17:04:08

在您的useEffect中,您已经在调用getSimById()并存储结果,因此以后不需要再次调用它。

相反,尝试迭代simResult数组。它应该有你想要参考的价值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63473300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档