大家好,
我有一个map
函数,该函数将数据数组映射到我的状态之一内。 map函数在第一次加载时工作正常,但是当我开始在数组中“推送”数据时,会出现以下错误:
TypeError: Cannot read property 'map' of undefined
我不知道下一步该怎么做,因为我绝对不知道我在做什么错。
我的组件
import React, { Component } from 'react';
import { Button, Table, Input, InputGroup, Container } from 'reactstrap';
import { Person } from './components/Person';
import { getFetch, postFetch } from './utilities/ApiCalls';
export default class App extends Component {
state = {
fetchData: null,
success: undefined,
name: undefined,
birthday: undefined
};
async componentDidMount() {
const response = await getFetch('http://127.0.0.1:8000/api/birthday/all');
this.setState({
fetchData: response
});
}
addPerson = async () => {
const { name, birthday, fetchData } = this.state;
const response = await postFetch('http://127.0.0.1:8000/api/birthday/create', {
name: name,
birthday: birthday
});
this.setState({
fetchData: [...fetchData.data, {
id: response.data.id,
naam: response.data.naam,
geboortedatum: response.data.geboortedatum
}]
});
};
render() {
const { fetchData } = this.state;
return (
<Container>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Age</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{fetchData ? fetchData.data.map((person) => (
<Person key={person.id} name={person.naam} date={person.geboortedatum}/>
)) : <Person name="Loading..." date="0"/>
}
</tbody>
</Table>
<InputGroup>
<Input type="text" onChange={(e) => this.setState({ name: e.target.value })}/>
<Input type="date" onChange={(e) => this.setState({ birthday: e.target.value })}/>
</InputGroup>
<Button onClick={this.addPerson}>Add Person</Button>
</Container>
);
}
}
感谢您的帮助!
答案 0 :(得分:1)
最初,从您的渲染方法开始,您希望fetchData
成为object
,并且将data
作为键名,该键名将是一个数组。但是您的addPerson
函数会将this.state.fetchData
更改为array.
,您可以将addPerson
中的setState更新为
fetchData: { data: [...fetchData.data, { id: res.data.id ... }] }