如何解析 JSON 响应并将值存储在数组中
How to parse JSON response and store values inside a array
我正在使用 react-select 异步从通过 API 传递的输入加载选项。我得到 JSON 响应,其中有一个列表,其中有一个字段 "FullName" 我正在尝试遍历 JSON 文件并将所有字段名称存储在一个数组中。然后将该数组作为选项返回。
在 JSON 中有一个列表,该列表包含结果,每个数字都有一个 FullName
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: unexpected end of data at line 1 of the column 1 of JSON data catch the hoop
这是一个 CORS 策略问题。因为我使用的 api 是外部的并且与我的 url 不匹配,所以没有看到 JSON 响应。我切换到在后端调用 api,因为服务器到服务器没有 CORS。
我正在使用 react-select 异步从通过 API 传递的输入加载选项。我得到 JSON 响应,其中有一个列表,其中有一个字段 "FullName" 我正在尝试遍历 JSON 文件并将所有字段名称存储在一个数组中。然后将该数组作为选项返回。
在 JSON 中有一个列表,该列表包含结果,每个数字都有一个 FullName
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: unexpected end of data at line 1 of the column 1 of JSON data catch the hoop
这是一个 CORS 策略问题。因为我使用的 api 是外部的并且与我的 url 不匹配,所以没有看到 JSON 响应。我切换到在后端调用 api,因为服务器到服务器没有 CORS。