【问题标题】:eg - Component rerenders after input value is changed ? How to correct it例如 - 输入值更改后组件重新呈现?如何纠正它
【发布时间】:2020-12-28 22:43:24
【问题描述】:

实际上,我通过单击提交单击按钮并将该对象推送到数组名称 biodata 中并将数组排序为对象的追随者数量(在 useeffect() 中)来传递对象 问题是在我在输入框中进行一些更改之前,它不会渲染排序数组 从“反应”导入反应 从“反应”导入 {useState,useEffect}

import axios from 'axios';
function Search(){

const [searchkeyword,inputchange] = useState("");
const [biodata,setbiodata] =useState([]);

   const load=(e)=>{
       axios.get(`https://api.github.com/users/${searchkeyword}`).
       then((response)=>setbiodata((biodata)=>[...biodata,response.data])).catch((err)=>console.log(err.message))
       e.preventDefault();
    }
   function compare( a, b ) {
    if ( a.followers > b.followers ){
      return -1;
    }
    if ( a.followers < b.followers ){
      return 1;
    }
    return 0;
  }
   useEffect(()=>{
       
       document.getElementById("myform").reset()
       biodata.sort(compare);
       setbiodata(biodata)
       console.log("cahnge")
       
   },[biodata])

    return(
        <div>
         <form id="myform">
        <input type="text" id="a" onChange={(e)=>{inputchange(e.target.value)}} ></input>
        <button type="submit" onClick={load}>Click</button>
        </form>
        { biodata.length>0  &&
             biodata.map((e)=>{
                 return(
                     <div key={e.id}> 
                         <p>{e.login}</p>
                         <p>{e.followers}</p>
                        </div>

                 );
             })
        }
        </div>
    );
}


export default Search;

【问题讨论】:

    标签: reactjs react-hooks use-effect


    【解决方案1】:

    当它渲染排序后的数组时,它实际上是排序的吗?我现在无法对其进行测试,但您可能希望将您的 useEffect 更改为:

    document.getElementById("myform").reset()
       const sortedBioData = biodata.sort(compare);
       setbiodata(sortedBioData)
       console.log("cahnge")
    

    请注意,在 useEffect 中更改 biodata 状态可能会导致无限状态循环

    【讨论】:

    • 对进行此更改没有影响。实际上它正在对数组进行排序,但在我对输入进行一些更改之前不会在 ui 上重新渲染
    猜你喜欢
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2020-10-19
    • 2021-08-28
    • 2017-11-18
    • 2021-01-24
    • 2021-01-12
    • 2021-01-26
    相关资源
    最近更新 更多