此问题在此处已有答案:
How do I return the response from an asynchronous call?(44个答案)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference(7个答案)
3天前关闭。
我有一个在几个文件中重复的函数,我想通过创建一个带有该函数的文件并将其导入到需要使用它的组件中来整理一下代码。
import React,{ useState, useMemo } from "react";
import * as d3 from 'd3';
import 'w3-css/w3.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {faBolt} from '@fortawesome/free-solid-svg-icons';
import GetData from '../functions/GetData'
const numbatt = 2;
const file = 'bmsfault.csv';
const slice = -6;
function BMS() {
const values = GetData(numbatt, file, slice);
/*const [temp, setTemp] = useState([]);
const values = useMemo(() => {
const fetchData = async () => {
const valuesArray = [];
for (let i = 0; i < numbatt; i++) {
const csvfile = './sftp/000000004b11cf51/data/batt' + (i) + '/' + file;
await d3.csv(csvfile).then((results) => {
results.map((d) => {
valuesArray.push(Object.values(d.value));
return () => undefined;
});
setTemp(temp.push(valuesArray.slice(slice)));
});
};
}
fetchData()
.catch(console.error);;
//console.log('temp',temp);
return(temp);
}, []);*/
console.log('values',values);
我复制了上面注解的代码的重复部分,并创建了一个新的.js文件,其中包含GetData函数,然后在需要读取数据的不同位置调用它。不知何故,返回的值是一个空数组。
import { useState, useMemo } from "react";
import * as d3 from 'd3';
function GetData(props) {
const [temp, setTemp] = useState([]);
const values = useMemo(() => {
const fetchData = async () => {
const valuesArray = [];
for (let i = 0; i < props.numbatt; i++) {
const csvfile = './sftp/000000004b11cf51/data/batt' + (i) + '/' + props.file;
await d3.csv(csvfile).then((results) => {
results.map((d) => {
valuesArray.push(Object.values(d.value));
return () => undefined;
});
setTemp(temp.push(valuesArray.slice(props.slice)));
});
};
}
fetchData()
.catch(console.error);;
//console.log('temp',temp);
return(temp);
}, []);
//console.log('values',values);
return values;
}
export default GetData
1条答案
按热度按时间06odsfpq1#
你的
fetchData
是异步的。它返回承诺。替换此
与