我正在使用react-select异步从通过API传递的输入加载选项。我收到 JSON 响应,其中有一个列表,其中有一个字段“FullName” 我试图遍历 JSON 文件并将所有字段名称存储在一个数组中。然后该数组作为选项返回。
JSON 中有一个列表,该列表包含结果,每个数字都有一个全名
JSON 响应的格式:
version:
status:
-status code
-status message
error:
result:
-paginate
list:
-0
--FullName
下面是我的类(class),我展示了我认为问题出在 -----
class ReactSelectExample extends Component {
constructor(props, context) {
super(props, context);
this.state = {
selectedOption: {}
}
}
fetchData = (inputValue, callback) => {
if (!inputValue) {
callback([]);
} else {
setTimeout(() => {
fetch("-----API URL----" + inputValue, {
method: "GET",
})
.then((resp) => {
return resp.json()
})
----------------
.then((data) => {
const tempArray = [];
data.forEach((element) => {
tempArray.push({ label: `${element.fullname}`, value: element.FullName });
});
callback(tempArray);
---------------
})
.catch((error) => {
console.log(error, "catch the hoop")
});
});
}
}
onSearchChange = (selectedOption) => {
if (selectedOption) {
this.setState({
selectedOption
});
}
};
render() {
return ( <div>
<AsyncSelect
value={this.state.selectedOption}
loadOptions={this.fetchData}
placeholder="Admin Name"
onChange={(e) => {
this.onSearchChange(e);
}}
defaultOptions={false}
/>
</div>)
}
}
当我启动它并搜索时,我看到的所有内容都在加载,但没有加载带有名称的选项。当我检查页面时出现错误
JSON.parse:JSON 数据第 1 列第 1 行数据意外结束
最佳答案
这是 CORS 政策问题。因为我使用的 api 是外部的并且与我的 url 不匹配,所以看不到 JSON 响应。我转而在后端调用 api,因为服务器到服务器没有 CORS。
关于javascript - 如何解析 JSON 响应并将值存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58378758/