在ReactJS中将函数称为嵌套状态对象

时间:2019-03-20 08:25:21

标签: javascript reactjs

我正在执行获取请求,以接收我所有的 json 数据并将其存储在当前状态下,之后我想调用一个函数,该函数将更改其中一个嵌套json对象的内容数组。

我看过类似的问题,例如this one,但似乎无法弄清楚。

这是我收到的json数据的结构:

[
   {
      "id":"George",
      "top":[
         {
            "performance":4289000,
            "day":"Sunday",
            "penalties":"none"
         },
         {
            "performance":4259000,
            "day":"Saturday",
            "penalties":"two"
         }
      ]
   },
   {
      "id":"Maya",
      "top":[
         {
            "performance":4139000,
            "day":"Monday",
            "penalties":"none"
         },
         {
            "performance":4439000,
            "day":"Sunday",
            "penalties":"one"
         }
      ]
   }
]

如何在数组 top performance 对象上执行功能并将其传递到完整状态?例如,如何在此嵌套对象上调用将毫秒转换为持续时间的函数?

这是我更改持续时间的功能:

function parseMillisecondsIntoReadableTime(milliseconds) {
    //Get hours from milliseconds
    var hours = milliseconds / (1000 * 60 * 60);
    var absoluteHours = Math.floor(hours);
    var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
    //Get remainder from hours and convert to minutes
    var minutes = (hours - absoluteHours) * 60;
    var absoluteMinutes = Math.floor(minutes);
    var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
    //Get remainder from minutes and convert to seconds
    var seconds = (minutes - absoluteMinutes) * 60;
    var absoluteSeconds = Math.floor(seconds);
    var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
    return h + ':' + m + ':' + s;
}

问题:

  

如何将函数 parseMillisecondsIntoReadableTime 应用到 top 数组内的 performance 对象并将其设置为 this.state < / strong>我可以将其呈现到html页面吗?

3 个答案:

答案 0 :(得分:1)

通过遍历数组中的所有元素和嵌套的top数组中的所有元素,并通过调用以下命令覆盖performance,可以在将数据置于状态之前进行处理: parseMillisecondsIntoReadableTime

示例

const data = [
  {
    id: "George",
    top: [
      {
        performance: 4289000,
        day: "Sunday",
        penalties: "none"
      },
      {
        performance: 4259000,
        day: "Saturday",
        penalties: "two"
      }
    ]
  },
  {
    id: "Maya",
    top: [
      {
        performance: 4139000,
        day: "Monday",
        penalties: "none"
      },
      {
        performance: 4439000,
        day: "Sunday",
        penalties: "one"
      }
    ]
  }
];

function getData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(data);
    }, 1000);
  });
}

function parseMillisecondsIntoReadableTime(duration) {
  let seconds = Math.floor((duration / 1000) % 60);
  let minutes = Math.floor((duration / (1000 * 60)) % 60);
  let hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds;
}

class App extends React.Component {
  state = {
    data: null
  };

  componentDidMount() {
    getData().then(data => {
      data.forEach(item => {
        item.top.forEach(obj => {
          obj.performance = parseMillisecondsIntoReadableTime(obj.performance);
        });
      });

      this.setState({ data });
    });
  }

  render() {
    const { data } = this.state;

    if (data === null) {
      return null;
    }
    return <div>{JSON.stringify(data)}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

答案 1 :(得分:1)

这是我们不应该改变状态的规则。

因此,由于这个原因,您必须更新嵌套状态performance键:

  1. 首先,您必须遍历当前状态数据,以便创建数组的副本。
  2. 第二,您可以使用performance函数覆盖parseMillisecondsIntoReadableTime键。
  3. 最后,有了新状态,您可以使用newState常量(来自下面的示例)中的数据来更新组件状态。

示例如何构建没有突变的新阵列):

// Credits to @Tholle, for refactoring the below function.
const parseMillisecondsIntoReadableTime = duration => {
  let seconds = Math.floor((duration / 1000) % 60);
  let minutes = Math.floor((duration / (1000 * 60)) % 60);
  let hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds;
}

const state = [{
    "id": "George",
    "top": [{
      "performance": 4289000,
      "day": "Sunday",
      "penalties": "none"
    }, {
      "performance": 4259000,
      "day": "Saturday",
      "penalties": "two"
    }]
  },
  {
    "id": "Maya",
    "top": [{
      "performance": 4139000,
      "day": "Monday",
      "penalties": "none"
    }, {
      "performance": 4439000,
      "day": "Sunday",
      "penalties": "one"
    }]
  }
]

const newState = state.map(item => ({
  ...item,
  top: item.top.map(top => ({
    ...top,
    performance: parseMillisecondsIntoReadableTime(top.performance)
  }))
}))

console.log(newState)

如果您有任何疑问,请随时提问。

答案 2 :(得分:0)

如果解析后的d = [[1,2],[3],[0]]值仅用于演示目的,则可以像performance一样在parseMillisecondsIntoReadableTime中调用render

filter