3 回答

TA貢獻1893條經(jīng)驗 獲得超10個贊
您應該使用state
而不是props
因為您將 API 響應設置為state
render() { const { events } = this.state; ...

TA貢獻1836條經(jīng)驗 獲得超3個贊
在狀態(tài)上設置
events
為空數(shù)組從 state 而不是 props 中讀取事件:
(可選)使用
loading
state 顯示加載器并確定何時獲取數(shù)據(jù)。
class DisplayEvent extends Component {
constructor(props) {
super(props);
this.state = { value: '', loading: true, events: [] }; // use array here
}
componentDidMount() {
this.setState({ loading: true });
axios
.get('http://127.0.0.1:8000/api/events')
.then(response => {
this.setState({ events: response.data, loading: false });
})
.catch(function(error) {
console.log(error);
this.setState({loading: false});
});
}
render() {
const { events, loading } = this.state; // get events from the state
return (
<div>
<h1>Events</h1>
<table className="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Event Name</td>
<td>Event Description</td>
<td width="200px">Actions</td>
</tr>
</thead>
<tbody>
{loading ? (
<p>Loading events...</p>
) : (
events.map(event => {
return <Event key={event.id} event={event} onDelete={this.onDelete} onEdit={this.onEdit} />;
})
)}
</tbody>
</table>
</div>
);
}
}

TA貢獻1851條經(jīng)驗 獲得超5個贊
events如果 API 返回的數(shù)據(jù)是,則設置一個空數(shù)組undefined。現(xiàn)在您還沒有添加條件來處理這種情況。如果您undefined從響應中獲得一個不是數(shù)組的值,這就是它顯示此錯誤的原因。
this.setState({ events: response.data || [] });
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/events')
.then(response => {
this.setState({ events: response.data || [] });
})
.catch(function (error) {
console.log(error);
})
};
更新
const events = this.props.events || [];
添加回答
舉報