【发布时间】:2020-07-03 02:35:19
【问题描述】:
我是 Reactjs 开发的新手,目前正在从事一个有趣的个人项目。所以我有 JSON 文件,内容是:
{
"btcinr": {
"base_unit": "btc",
"quote_unit": "inr",
"low": "479200.0",
"high": "509949.0",
"last": "500003.0",
"type": "SPOT",
"open": 493000.0,
"volume": "48.0567",
"sell": "503000.0",
"buy": "500003.0",
"at": 1584867246,
"name": "BTC/INR"
}
}
我的渲染方法中有以下代码:
import React from "react";
class App extends React.Component {
constructor(props){
super(props);
this.state = {
items : [],
isLoading: true,
}
}
componentDidMount() {
fetch('JSON API LINK')
.then(res => res.json())
.then((data) => {
this.setState({
items: data,
isLoading: false,
})
})
.catch(console.log)
}
render() {
const list = this.state.items.btcinr && Object.keys(this.state.items.btcinr);
console.log(list);
return (
<div>
{this.state.isLoading ? <h1>Fetching data </h1> :
list.map(
(ticker) =>
<li>{ticker}</li>
)
}
</div>
);}
}
export default App;
我想要输出的是 last 的值。但是当我通过 list.last 我得到错误
无法读取 undefined 的 proparty“last”。
【问题讨论】:
-
您需要通过向组件传递属性来构建组件。或者在 state 中构建值,但留到以后,看看这里如何将 props 传递给组件。 How to pass props from one class to another in React.js
-
你能粘贴你的 JSX 文件的完整代码吗?
-
list是 keys 的数组。你可能想使用this.state.items.btcinr.last -
@MuhammadHaseeb 我已经编辑了代码并插入了完整的代码。