【发布时间】:2019-12-22 13:58:55
【问题描述】:
我已经使用 ASP.NET 创建了一个 API,并且我有一个运行 React 的网站。我想通过来自 API 的获取请求来显示数据检索,以使用 Axios 进行 React。该网站有一种使用两个 cookie 的身份验证方法。我可以让 Axios 从 https://jsonplaceholder.typicode.com/users 获取数据,但是当我使用相同的代码时,我会收到错误:未捕获(承诺)TypeError:data.map 不是函数。
如上所述,我已尝试使用占位符,效果很好,但似乎无法从我的 API 获取数据,这让我相信问题出在 cookie 上。我还尝试了一些 Google 搜索,结果返回我应该包含 withCredentials: true,但这并没有解决问题。
这是我的 API 中的函数:
public JsonResult YearlyManagersJSON(int year = 0)
{
if (year < 2000 || year > DateTime.Today.Year)
year = DateTime.Today.Year;
var startDate = new DateTime(year, 1, 1);
var endDate = new DateTime(year + 1, 1, 1);
var bonds = this.getOverviewData(ReportType.BONDS, startDate, endDate);
var bondsSum = bonds.Sum(m => m.Aggregate);
var viewData = new TopLeadManagerViewData
{
Title = String.Format("Top Managers in {0}", startDate.Year),
Currency = SiteHelper.getCurrencyToUse(),
Bonds = Enumerable.Select(bonds, m => new ManagerSummary()
{
NumberOfIssues = (int)m.Aggregate2,
TotalAmount = m.Aggregate * 1000000,
Name = m.Group.ToString(),
Share = 100.0m * m.Aggregate / bondsSum
}),
};
return this.Json(viewData, JsonRequestBehavior.AllowGet);
}
这会返回一个 JSON,我已经使用 Postman 进行了检查。然后我尝试使用 axios 访问数据。
state = {
yearlyBonds: []
}
componentDidMount() {
axios.get(
'http://localhost/Stamdata.Web/LeagueTable/YearlyManagersJSON',
{ withCredentials: true }
)
.then(res => {
const yearlyBonds = res.data;
this.setState({ yearlyBonds });
})
}
render() {
return (
// Tags removed for simplicity
<ListTable data={this.state.yearlyBonds.Bonds} />
然后将数据向下传递到组件中
function ListTable(props) {
const { classes, header, data } = props;
return(
// Tags removed for simplicity
<TableBody>
{data.map((x, i) => {
return(
<TableRow key={i}>
<TableCell scope="row">{x.Name}</TableCell>
<TableCell scope="row">{x.TotalAmount}</TableCell>
<TableCell scope="row">{x.Share}</TableCell>
<TableCell scope="row">{x.NumberOfIssues}</TableCell>
</TableRow>
)
})}
</TableBody>
所以,这会返回错误
“Uncaught (in promise) TypeError: data.map is not a function”,我想显示检索到的数据。
【问题讨论】:
标签: c# reactjs axios api-design