【问题标题】:Access the json object in react by using typescript使用 typescript 访问 react 中的 json 对象
【发布时间】:2020-12-25 07:30:07
【问题描述】:

我以前从未使用过打字稿,但在这个项目中我需要使用它。我有我的 api,它正在向我发送数据,如下所示。 Api 无法更改,因为它是客户的 api,他不允许我更改它。问题是当我访问实际值时。2020-01-01 它给了我解析错误。如何使用 typescript 访问这个 json 对象。我需要在函数中登录,它与函数中出现的年份和日期匹配所有实际值,并返回匹配的实际值,否则它将返回“无”。我不知道我该怎么做。我需要在 2 小时内将其交付给客户。

//Backend
actuals: {
  "2020-01-01": {
    value: 1,
  },
  "2020-02-01": {
    value: 2,
  },
},

//Frontend
//Table
<tbody>
                                {dataSeries.map(
                                    (
                                        data: {
                                            name: string;
                                            actuals: JSON;
                                        },
                                        index: number
                                    ) => (
                                        <tr key={index}>
                                            {console.log(data)}
                                            <td>{data.name}</td>
                                            <td>
                                                {matchYearAndMonth(
                                                    monthBackward(0)
                                                        .currentyear,
                                                    monthBackward(0).month,
                                                    data.actuals
                                                )}
                                            </td>
                                            <td>
                                                {matchYearAndMonth(
                                                    monthBackward(1)
                                                        .currentyear,
                                                    monthBackward(1).month,
                                                    data.actuals
                                                )}
                                            </td>
                                        </tr>
                                    )
                                )}
</tbody>

//MatchYearAndMonth function

    const matchYearAndMonth = (year: number, month: number, actuals: JSON) => {
        console.log(actuals.2020-01-01);
        return year;
    };

【问题讨论】:

  • 尝试使用actuals["2020-01-01"]访问另外,也许将实际类型更改为actuals: {[key: string]: object}之类的东西
  • 已经试过了。还是解析错误
  • 究竟是什么错误?你能附上问题中的错误吗?
  • 如果我尝试像 actuals.2020-01-01 一样访问然后我得到“解析错误:','预期”但是如果我访问实际 [“2020-01-01”] 我会不会出错,但会在控制台中未定义。
  • 试试 console.log(actuals, actuals["2020-01-01"]) 看看实际是否真的被传递给函数。

标签: javascript json reactjs typescript api


【解决方案1】:
type ActualsType = {[key: string]: {[key: string]: any, value: 1,}};
type DataSeriesType = {actuals: ActualsType, name: string};

function dateToStr(d=new Date()) {
  const y = d.getFullYear(),
        m = (d.getMonth()+1+"").padStart(2, "0"),
        day = (d.getDate()+"").padStart(2, "0");

  return `${y}-${m}-${day}`;
}

const today = new Date();
today.setDate(1);

const dataSeries: Array<DataSeriesType> = [
  {name: "Test 1", actuals: {
    "2020-01-01": {
      value: 1,
    },
    "2020-02-01": {
      value: 2,
    },
    "2020-09-01": {
      value: 9,
    },
  }},
  {name: "Test 2", actuals: {
    "2019-09-01": {
      value: 1.2,
    },
    "2019-10-01": {
      value: 2.2,
    },
  }},
];

const matchYearAndMonth = (year: number, month: number, actuals: ActualsType) => {
  const value = actuals[dateToStr(today)] ? actuals[dateToStr(today)]?.value : undefined;
  console.log(value);
  return {year, month, value};
};

dataSeries.map((v, i) => {
  const parsed = matchYearAndMonth(2020, i, v.actuals);
  // console.log(parsed);
})

【讨论】:

  • 我无法按点访问值。实际值["2020-01-01"].value 不起作用。
  • 您可以使用actuals["2020-01-01"]["value"],但我认为它未定义,这就是原因。所以你可以检查matchYearAndMonth函数const value = ....
  • 不工作它给了我错误“对象”类型上不存在属性“值”
  • 在答案顶部检查我已经更新了类型
猜你喜欢
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 2020-10-27
  • 1970-01-01
  • 2016-07-04
  • 2021-01-01
  • 1970-01-01
相关资源
最近更新 更多