【发布时间】:2018-07-28 11:20:53
【问题描述】:
我最终使用 fetch 从我的 React API 中获取数据,并在我的控制台中获取了 JSON。现在我有另一个挑战。
我有一个搜索组件,我想在我得到的 JSON 中搜索并在屏幕上显示结果。我该怎么做?
这是我目前写的:
class Global extends Component {
constructor(props) {
super(props);
this.state = {
query: "",
items: []
};
}
search() {
let url = "/*my url*/";
fetch(url, {
method: "GET", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json; charset=utf-8",
Authorization: "Bearer /*my key*/",
"Access-Control-Allow-Headers": "accept"
}
// redirect: "follow", // manual, *follow, error
// referrer: "no-referrer", // no-referrer, *client
// body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json())
.then(json => console.log(json));
}
render() {
return (
<div className="global">
<h2>book Explore!</h2>
<FormGroup>
<InputGroup>
<FormControl
type="text"
placeholder="Search for a Branches"
onChange={event => this.setState({ query: event.target.value })}
onKeyPress={event => {
if (event.key === "Enter") {
this.search();
}
}}
/>
<InputGroup.Addon onClick={() => this.search()}>
<Glyphicon glyph="search" />
</InputGroup.Addon>
</InputGroup>
<Gallery items={this.state.items} />
</FormGroup>
</div>
);
}
}
【问题讨论】:
-
请贴出 JSON 的形状。
-
{ "status": { "response_code": 0, "response_message": "OK", "response_extra": null }, "data": [ { "BranchID": 1, "Name" :“شعبه خورشید”,“RegionNames”:“نظر،فیض،میر،آپادانا،آبشار”,“纬度”:“32.637717”,“经度”:“51.655215”,“图像”:“khorshid.jpg”,“CreateDate ": "2018-06-09 15:24:20", "状态": 1 }, ...
-
实际上,换句话说,我有一个数组,我将它保存在“数据”变量中。现在我想在这个数组中搜索,我该怎么办???
标签: reactjs api ecmascript-6 fetch