【发布时间】:2021-12-29 07:31:07
【问题描述】:
我对@987654322@ 很陌生。我正在尝试创建一个包含数据数组的表,并且要显示的数据使用set 方法从多维数组中检索特定值。我使用useState 和Axios 来调用API。我还为平板电脑 UI 导入了一个名为 'material-table' 的组件。但是,每当尝试显示数组中的变量时,我都会收到一条错误消息“ReferenceError: Cannot access 'finalprice' before initialization”
这是我的 2 个主要 JS 文件。
CallAPI.js 是主要检索API数据的函数文件。
mtable.js 是组件表,用于从 API 文件中导入数据并插入到材料表中。
CallAPI.js 文件:
import Axios from "axios";
import React, { useState, Component } from "react";
import { StyleSheet, TextInput, SafeAreaView } from 'react-native';
import './ButtonLogs.css';
class ComponentMain extends Component{
render(){
return(
<div>
</div>
)
}
}
function CallAPI () {
const [DPID, setText] = useState('');
const [Quote, setText1] = useState('');
let gcmpapi =
"https://blablabla/"+ DPID +"/blablabla"; // declare a variable to store the URL
const [finalprice,setGCMP1] = useState({
id: 1,
title: 'Final Price',
Quote: '999999',
SalesOrder: '999999',
GCMP: finalprice, // <===== this is where cause the page throwing the error message.
},) // declare a variable to store the array
const callgcmpapi = () => { //assign a variable for a call function
Axios.get (gcmpapi).then(
(response) => {
console.log(response);
setGCMP1(response.data.Data.PurchaseSummary.PriceSummary.FinalPrice); // call the value from the multi-dimensional array
})
};
return (
(<div className='MainButton'>
<button class="button button1"onClick={() =>{
callgcmpapi()
}}>Extract API results</button>
</div>
);
}
export {CallAPI};
export default ComponentMain;
MTable.js 文件:
import MaterialTable from 'material-table';
import { CallAPI } from "./CallAPI";
const MTable = () => {
//...
const columns = [
{ title: 'GCMP (DPID)', field: 'GCMP' }
];
return (
<div style={
{ maxWidth: '100%' }}>
<MaterialTable columns={columns} data={CallAPI} title='Endpoints Directory' />
</div>
);
};
export default MTable;
错误信息: ReferenceError: Cannot access 'finalprice' before initialization
【问题讨论】:
-
您正在尝试使用
finalprice的值来设置finalprice的值。当您创建该对象时,您希望GCMP属性具有什么值,为什么?它应该有什么价值? -
嗨@David,我正在尝试从已设置为
setGCMP1的维度数组中携带值finalprice,并将其声明为数组中的GCMP。有什么建议我可以继续吗?我对 GCMP 的期望输出:12345 setGCMP1的数据
标签: reactjs api multidimensional-array react-hooks fetch-api