0

我有一个函数可以从 api ( getactivity() ) 中提取和排序数据,然后以正确的格式 ( answer1 ) 返回排序后的数据。但是我遇到了一个问题..当我尝试运行以获取数据时,它一直没有返回任何内容..

这是完整的代码,

import React, { Component, Fragment } from 'react';
import axios from 'axios';
import Pusher from 'pusher-js';
import Stats from '../../components/Stats';
import Layout from '../../components/Layout';

const choices = ['Monday', 'Tusday', 'Wensday', 'Thursday', 'Firday'];

let curr = new Date 
let week = []

for (let i = 1; i <= 7; i++) {
  let first = curr.getDate() - curr.getDay() + i 
  let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
  week.push(day)
}

// console.log(week)

function getactivity() {

    axios.get('/api/profiles/stats')
      .then(response => {
        const activty = response.data["Drinks"]

        var o = {};
        activty.forEach((i) => {
          var Date = i.Date;
          i.count = parseInt(i.count)
          if (!o[Date]) {
            return o[Date] = i
          }
          return o[Date].count = o[Date].count + i.count
        })

        var res = []
        Object.keys(o).forEach((key) => {
         res.push(o[key])
        })

        var answer1 = ""
        for (const x of res) {
            if(week.includes(x.Date)) {
                answer1 = answer1 + "[" + x.Date + "]" + ": " + x.count + ", "
            }
        }
        console.log("return: " + answer1)
        return answer1
    }, error => {
    console.log(error);
  });
}

console.log("act: " + getactivity())

class IndexPage extends Component {

    state = { answers: getactivity() }

  render() {

    return (
      <Layout pageTitle="AA Drinking activity">
        <main className="container-fluid position-absolute h-100 bg-light">
          <div className="row position-absolute w-100 h-100">
            <section className="col-md-5 position-relative d-flex flex-wrap h-100 align-items-start align-content-between bg-white px-0">
                <Stats choices={choices} stats={this.state.answers} />
            </section>

          </div>
        </main>
      </Layout>
    );
  }

};

export default () => (
    <Fragment>
        <IndexPage />
        <style global jsx>{`

            .custom-control-label {
                background: transparent;
                color: #999;
                font-size: 2rem;
                font-weight: 500;
                cursor: pointer;
                line-height: 2.25rem;
            }

            .custom-control-label:before, .custom-control-label:after {
                top: 0;
                left: -10px;
                height: 2.25rem;
                width: 2.25rem;
                cursor: pointer;
                box-shadow: none !important;
            }

            .custom-control-label.checked {
                color: #007bff !important;
            }

            button.btn {
                letter-spacing: 1px;
                font-size: 1rem;
                font-weight: 600;
            }

        `}</style>
    </Fragment>
);

console.log() 的顺序确实显示了我认为应该的方式,它按顺序打印

行为:未定义

返回:[2020-12-08]:10,[2020-12-09]:7,[2020-12-10]:4,[2020-12-11]:3,

我会假设退货将首先打印。

4

1 回答 1

0

您收到此错误是因为 javascript 异步运行。它不会等待来自服务器的响应(由您的 axios 调用做出)继续执行。在你的情况下,一个解决方案是将你想要运行的代码放在一个链中,然后像这样:

axios.get('/api/profiles/stats')
  .then(response => {
    // the code run directly after the axios call...
  }.then(activity=>{
    console.log("act: "+activity);
  });

如果你想在函数中使用 getActivity,你可以使用 async/await。此链接应该会有所帮助https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

于 2020-12-12T02:16:55.777 回答