我有一个下面的代码,我试图在React表单中填充下拉列表选择。
我的渲染组件:
<Form.Control as="select">
{this.state.originCity.map(name => (
<option key={name.CityName} value={name.CityCode}>
{name.CityName}
</option>
))}
</Form.Control>;
我到originCity的数据如下:
console.log("Selected State for Origin: " + e.target.value);
axios
.get(`http://localhost:3010/cityNames?name=${e.target.value}`)
.then(response => {
var arr = [];
for (var i in response.data) {
arr.push(response.data[i]);
}
this.setState({ originCity: arr });
});
我在控制台日志中获取的数据是
[ {CityName: "Albion", CityCode: 240020}
{CityName: "Alma (e)", CityCode: 240031}
{CityName: "Alpena (e)", CityCode: 240042} ]
但是我在浏览器中收到如下错误:
对象作为React子对象无效(找到:带有键{CityName,CityCode}的对象)。如果要渲染子级集合,请改用数组。
答案 0 :(得分:1)
如果您已经得到一个数组,那么为什么要进行循环插入? 直接将数组传递到状态
axios
.get(`http://localhost:3010/cityNames?name=${e.target.value}`)
.then(response => {
let arr = response.data;
this.setState({originCity:arr})