首页 > 解决方案 > 在 Promise React 中更改接收到的数据

问题描述

我的 React 应用程序接收以下 JSON 格式的日期:

[
{"date":"20201001","time":"001100"},
{"date":"20201001","time":"001200"},
{"date":"20201001","time":"001300"}
]

我想以正常格式将日期和时间保存到 React 状态 - 日期加时间。所以它应该只是这样的日期:

[
{"date":"2020-10-01 00:11:00"},
{"date":"2020-10-01 00:12:00"},
{"date":"2020-10-01 00:13:00"}
]

这是我的 App.js 代码:


import React from 'react';
import { render } from 'react-dom';
import { timeParse } from "d3-time-format";

class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {datas: []};
    }

    componentDidMount() {
        this.getAllData();
    }

    getAllData() {
        fetch("http://localhost:8080/data")
            .then(response => response.json())
            .then((data) => { data = tt(data)})
            .then((data) => {
                this.setState({datas: data});
            });
    };

    render() {
        if (this.state == null) {
            return <div>Loading data...</div>
        }
        return (
            <div>{this.state.datas ? this.state.datas.toString() : 'No data yet...'}</div>
        )
    }
}

function tt(d) {
    d.date = timeParse(d.date+d.time);
    return d;
};

const parseDateTime = timeParse("%Y%d%m%H%M%S");

render(
    <MyComponent />,
    document.getElementById("root")
);

export default MyComponent;

我认为以下代码行有问题:

.then((data) => { data = tt(data)})

但无法理解是什么。

我总是得到未修改的日期和时间,它从服务器收到的格式相同。

标签: reactjsd3.jsfetch

解决方案


您没有从.then((data) => { data = tt(data)}). 返回您正在为 Promise 链中的下一个 then-able 计算的新 DateTime。

如果data是一个数组,那么您将需要映射数据并tt在每个元素对象上调用实用程序函数。

.then((data) => {
  return data.map(tt);
})

更新

您正在从输入格式解析日期时间,但您还需要格式化输出。您不想改变映射的data元素,而是希望返回一个仅具有属性的对象。date

import { timeFormat, timeParse } from "d3-time-format";

...

const parseDateTime = timeParse("%Y%d%m%H%M%S");
const formatDateTime = timeFormat("%Y-%d-%m %H:%M:%S");

const tt = (d) => ({
  date: formatDateTime(parseDateTime(d.date + d.time))
});

...

getAllData() {
  fetch("http://localhost:8080/data")
    .then((response) => response.json())
    .then((datas) => datas.map(tt))
    .then((datas) => {
      this.setState({ datas });
    });
}

我建议还添加一个单独的加载状态,因为datas状态是一个定义的空数组,state不会为空。

完整示例:

const parseDateTime = timeParse("%Y%d%m%H%M%S");
const formatDateTime = timeFormat("%Y-%d-%m %H:%M:%S");

const tt = (d) => ({
  date: formatDateTime(parseDateTime(d.date + d.time))
});

class MyComponent extends React.Component {
  state = {
    datas: [],
    loading: false
  };

  componentDidMount() {
    this.getAllData();
  }

  getAllData() {
    this.setState({ loading: true });
    fetch("http://localhost:8080/data")
      .then((response) => response.json())
      .then((datas) => datas.map(tt))
      .then((datas) => {
        this.setState({ datas });
      })
      .finally(() => this.setState({ loading: false }));
  }

  render() {
    if (this.state.loading) {
      return <div>Loading data...</div>;
    }
    return (
      <div>
        {this.state.datas.length
          ? JSON.stringify(this.state.datas)
          : "No data yet..."}
      </div>
    );
  }
}

编辑changeing-recived-data-in-promise-react


推荐阅读