【问题标题】:Set state for a hook functional component inside another functional component为另一个功能组件内的钩子功能组件设置状态
【发布时间】:2019-10-12 20:28:24
【问题描述】:

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

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

搜索栏

用户写一个查询,当用户回车时,通过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 =&gt; setResults(["trytry"])) .then(console.log(results))results 没有改变值

标签: reactjs


【解决方案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;

【讨论】:

  • 谢谢,现在我明白了。但是如果我按照你说的做,GET 会在POST 之前执行。我需要相反的方法,否则用户在键盘上单击enter 它会返回错误的错误。
  • 如果您希望 POST 等待 GET 完成,您应该将其移动到第一个 GET 请求的 .then() 内或使用 async/await
  • 谢谢。我试过它似乎没有按预期工作:stackoverflow.com/questions/58365213/…
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 2019-08-15
  • 2019-12-08
  • 2020-11-19
  • 2020-02-12
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多