【发布时间】:2020-04-15 12:46:24
【问题描述】:
这里对 React 来说真的很新,我想做一个简单的搜索框,用户在其中提交“问题”,JSON 返回“结果”的值。
请求通过,我得到了响应,唯一我找不到的就是从中获取结果并将它们显示在前端。
class Search extends Component {
state = {
searchValue: "",
searchSection: "",
results: [],
// section: []
};
handleOnChange = event => {
this.setState({ searchValue: event.target.value });
};
handleSearch = () => {
this.makeApiCall(this.state.searchValue);
};
makeApiCall() {
fetch("http://example.com/json", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
question: (this.state.searchValue),
section: (this.state.searchSection),
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
return responseData
})
.then(results => this.setState({results: results.value}))
};
render() {
return (
<div id="main" className="py-16">
<label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-first-name">
Ask a question
</label>
<input
name="text"
type="text"
placeholder=""
onChange={event => this.handleOnChange(event)}
value={this.state.searchValue}
className="shadow-sm appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
/>
<button onClick={this.handleSearch} className="cursor-pointer mt-5 bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded-full shadow">Search</button>
// DISPLAYING THEM ON THE FRONT HERE
{this.state.results ? (
<div id="question-container">
{this.state.results.map((result) => (
<div className="result">
<h2>{result.title}</h2>
<p>{result.sentences}</p>
</div>
))}
</div>
) : (
<p>Can't find results for your question</p>
)}
</div>
);
}
}
export default Search;
我的 JSON 是这样的:
{
"request": {
"date_from": "",
"date_to": "",
"question": "User question here",
"section": null
},
"results": {
"docs": [
{
"title": " "
"section": " "
}
]
}
}
我需要显示来自 JSON 的多个问题
【问题讨论】: