我是 React js 的新手,而不是 JavaScript 开发人员,但可以破解我的解决方案。
我有提供简单数组的 Django API 网址。我可以成功地使用axios.get
来检索网址 json。但是我不知道如何使用map
将数组内容呈现为一个简单的列表。
我得到"TypeError: this.state.items.map is not a function"
我的代码:
import React from 'react';
import axios from 'axios';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: []
};
}
componentDidMount() {
axios.get('http://localhost:8800/?format=json')
.then(result => {
this.setState({ items: result.data });
});
}
render () {
return <ul>
{this.state.items.map(item =>
<li>{item} </li>)}
</ul>
}
}
export default App;
axios.get
的回应是这样的:
{
"users":"http://localhost:8800/users/?format=json",
"photos":"http://localhost:8800/photos/?format=json",
"teams":"http://localhost:8800/teams/?format=json"
}
我想将其呈现为 HTML 列表:
users - http://localhost:8800/users/?format=json,
photos - http://localhost:8800/photos/?format=json,
teams - http://localhost:8800/teams/?format=json
解决方案似乎是重写这部分代码。
render () {
return <ul>
{this.state.items.map((item, i) =>
<li key>{item} </li>)}
</ul>
}
我见过许多类似的问题和答案,但有各种各样的情况令人惊讶,没有一种适用于我的具体情况。
有人可以指出:
a( 我错过了什么和b( 它与什么一般的 React 和/或 JavaScript 原则有关,以及c( 我自己可以理解的任何文档?
你可以map
对象键
Object.keys(this.state.items)
将返回一个键数组["users", "photos", "teams"]
然后你可以map
这个数组
最好在组件渲染之前加载数据
https://jsfiddle.net/qnqeL65b/
更改componentWillMount()
componentDidMount()
render () {
return (
<ul>
{
Object.keys(this.state.items).map(key => {
return (
<li>
{key} - {this.state.items[key]}
</li>
)
}
}
</ul>
)
}
Array.prototype.map(( docs
Object.keys(( docs
正如其他人所说,Object
没有地图功能。相反,您可以执行以下操作:
Object.keys(this.state.items).map((key, index) => {
// do something
});
或者您也可以使用 for in
循环:
for (let key in this.state.items) {
// do something
}
如果您正在寻找key, value
访问权限,请尝试一下。
const obj = {
"first": "hello",
"second": "goodbye"
};
for (const [key, value] of Object.entries(obj)) {
console.log(`${key}, ${value}`);
}
// "first, hello"
// "second, goodbye"