【发布时间】:2022-09-30 00:36:16
【问题描述】:
我正在关注代码:https://codesandbox.io/s/cranky-leaf-2hupv?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js
该示例在我的 React 项目中有效,但是当我尝试将其调整为数据库中的值时,出现错误:
Uncaught (in promise) TypeError: response.data.map is not a function
我的 JSON 很简单
categories:
0:
Id: \"22\"
Name: \"Strategy\"
1:
Id: \"19\"
Name: \"Sports\"
2:
Id: \"27\"
Name: \"Branding\"
我已经修改了代码以适合我的 JSON,如下所示:
import React, { Component } from \'react\';
import axios from \'axios\';
export default class TestDropdown extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
display: \"\",
titles: [],
errorMsg: \'\'
};
}
toggle() {
this.setState(prevState => ({
dropdownOpen: !prevState.dropdownOpen
}));
}
componentDidMount = (e) => {
axios.get(\"https://mysite/devapi/categories.php\").then((response) =>
this.setState({
titles: response.data.map(({ Name }) => Name), /*error*/
display:
response.data[Math.floor(Math.random() * response.data.length)].title
})
);
};
render() {
const { display, titles } = this.state;
return (
<div className=\"container\">
<select defaultValue={display}>
{titles.map((Name) => (
<option key={Name} value={Name}>
{Name}
</option>
))}
</select>
</div>
);
}
}
我已经考虑过通过不访问“类别”来读取错误的 JSON 值是否是错误的,或者这是否与地图/列表有关。 我只需要名称值来填充选项。
来自初学者的感谢。
标签: javascript reactjs json get