【发布时间】:2019-10-12 20:28:24
【问题描述】:
我正在创建一个网站,用户可以在其中搜索查询并显示结果。
我创建了两个组件:Searchbar 和 ResultList,它们都是带有钩子的功能组件。
搜索栏
用户写一个查询,当用户回车时,通过axios POST请求发送到后端。 后端搜索相关查询并通过 axios GET 请求发回结果。 这是有效的。
结果列表
ResultList 状态由一个名为 results 的数组初始化。
我想要什么:
我想将results 数组设置为等于它从搜索栏中的 GET 请求返回的值。
搜索条码
function Searchbar() {
const [query, setQuery] = useState("");
function handlePostQuery(query){
var myParams = {
data: query
}
if (query != "") {
axios.post('http://localhost:5000/api/query', myParams)
.then(function(response){
var instructions_div = document.getElementsByClassName("instructions")[0];
instructions_div.style.display = "none";
console.log("Yes, it sends the query in JSON format to Flask");
//Perform action based on response
})
.catch(function(error){
console.log(error, "Error on AXIOS post");
//Perform action based on error
});
axios.get('http://localhost:5000/api/query')
.then(function (response) {
console.log("AXIOS GET")
console.log(response);
})
.catch(function (error) {
console.log(error);
});
} else {
alert("The search query cannot be empty")
}
}
return(
<div>
<SearchBar
onChange={(event) => setQuery(event)}
onRequestSearch={() => handlePostQuery(query)}
style={{
marginTop: 200,
marginLeft: 'auto',
marginRight: 'auto',
maxWidth: 800,
}}
/>
<ResultList /> # I think I should set the new state of Resultlist here but not sure how
</div>
)
}
export default Searchbar;
结果列表代码
function ResultList() {
const [results, setResults] = useState(["myemptyinitiallist"]);
if (results[0] !== "myemptyinitiallist") {
return (
<div className="resultlist">
This should appear only if results is different from "myemptyinitiallist"
</div>
)
} else {
return(
<h1>This should appear when results is empty</h1>
)
}
}
export default ResultList;
理想情况下我不想使用类组件。
【问题讨论】:
-
ResultList应该接受道具。它不对自己的状态负责。状态应该属于Searchbar -
另外你为什么直接从 handlePostQuery 干扰 DOM?
-
所以你建议在我的
Searchbar中添加const [results, setResuts]=useState(["myemptyinitiallist"]);。并在我的 axios GET 中做某事setResults(response)? -
我试过
axios.get('http://localhost:5000/api/query') .then(response => setResults(["trytry"])) .then(console.log(results))但results没有改变值
标签: reactjs