这是我的代码片段:
import React, { Component } from "react";
import axios from "axios";
import PlanDetails from "./PlanDetails";
import Pagination from "./Pagination";
import PropTypes from "prop-types"; //ES6
class Planner extends React.Component {
constructor(props) {
super(props);
this.state = {
destinations: [],
vacations: [],
itineraries: []
};
}
componentDidMount() {
const self = this;
axios
.get("sample.json")
.then(res => {
const data = res.data;
self.setState(data => {
destinations: data.destinations;
vacations: data.vacations;
itineraries: data.itineraries;
});
})
.catch(err => {});
}
render() {
return (
<div>
<h1>Planner</h1>
<PlanDetails />
<Pagination />
<ul>
{this.state.destinations.map(destination => (
<li key={destination.url}>{destination.text}</li>
))}
</ul>
</div>
);
}
}
Planner.propTypes = {};
export default Planner;
在上面的例子中,我试图在axios的帮助下从本地JSON获取值,我想在我的planner组件状态中更新响应。它没有反映出来。
有没有新的方法来实现这个?我是新来的反应。
setState
语法在您的代码中不正确。此外,您不需要self
,因为您正在使用axios .then
回调的箭头函数,它将上下文绑定到封闭范围
this.setState({
destinations: data.destinations,
vacations: data.vacations,
itineraries: data.itineraries
});