我是React的新手。我正面临这个错误。我有下面粘贴的代码。请帮助摆脱这个错误。
import React from 'react';
import { Card} from 'semantic-ui-react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`http://localhost:8080/locations`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<div class="ui stackable two column grid">
{ this.state.persons.map(person =>
<div class="column">
<Card
header={person.LOCATION}
/>
</div>)
}
</div>
)
}
}
错误消息粘贴在
下面TypeError: this.state.persons.map is not a function
PersonList.render
C:/Users/user/Desktop/src/Sample.js:22
19 | render() {
20 | return (
21 | <div class="ui stackable two column grid">
> 22 | { this.state.persons.map(person =>
23 | <div class="column">
console.log('data', res.data)
的输出:
{LOCATION: "CHINA9, SWEDEN9, CANADA9, austin, ", searchKey: {…}}
我请求任何人找出这个错误。
答案 0 :(得分:2)
您可以使用LOCATION
从.split(',')
字符串创建数组:
function render() {
const locationArr = this.state.persons.LOCATION
? this.state.persons.LOCATION.split(',')
: [];
return (
<div className="ui stackable two column grid">
{locationArr.map((location) => {
if (location !== ' ') {
return (
<div className="column">
<Card header={location} />
</div>
);
}
return null;
})}
</div>
);
}
答案 1 :(得分:0)
创建构造函数并声明您的状态
constructor(props){
super(props);
state = {
persons: ""
}
}
将状态更新更改为
axios.get(`http://localhost:8080/locations`)
.then(res => {
this.setState((prevState) => ({ persons : res.data.LOCATION }));
})
}
渲染方法
this.state.persons.split(",").map((person, index) => (
<div class="column" key={index}>
<Card
header={person}
/>
</div>
))
答案 2 :(得分:0)
您将this.state.persons
设置为res.data
,这可能是一个对象..您无法在对象上使用map
...
相反,您可能希望将对象推送到对象数组。像这样:
let persons = this.state.persons.slice()
persons.push(res.data)
this.setState({persons})
答案 3 :(得分:0)
render() {
let {
perons
} = this.state.perons;
if (perons.length == 0) {
return (
<div><h3>Loading data...</h3></div>
)
}
return (
<div class="ui stackable two column grid">
{ persons.map(person =>{
return(
<div class="column">
<Card
header={person.LOCATION}
/>
</div>
)
});
}
</div>
)
}