设置另一个功能组件内部的挂钩功能组件的状态

时间:2019-10-12 20:28:24

标签: reactjs

我正在创建一个网站,用户可以在其中搜索查询并显示结果。

我创建了两个组件:SearchbarResultList,它们都是带有钩子的功能组件。

搜索栏

用户编写一个查询,当用户输入时,查询通过axios POST请求发送到后端。 后端搜索相关查询,然后通过axios GET请求将结果发送回去。 这可以正常工作

结果列表

使用名为results的数组初始化ResultList状态。

我想要的东西: 我想将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;

理想:我不想使用类组件。

1 个答案:

答案 0 :(得分:1)

由于响应是从其父级处理的,因此它应该是ResultList中的道具

将代码更新为

function Searchbar() {
    const [query, setQuery] = useState("");
    const [results, setResults] = useState("");
...
    axios.get('http://localhost:5000/api/query')
        .then(function (response) {
          console.log("AXIOS GET")
          console.log(response);
          setResults(response.data); //set the value
        })
...
   <ResultList results={results}/>

在结果列表中

function ResultList({results}) { // destructuring props to get results
  //  const [results, setResults] = useState(["myemptyinitiallist"]); passed as props from parent

  if (results && results[0] !== "myemptyinitiallist") { // make sure the results is set before accessing value at [0]
        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;