简体   繁体   中英

How to re Re-render a child component when updating the state inside the child component

I'm just learning react and trying to create a simple project, I have a button that when it is clicked it sort the data which is coming from an API according to user age, when I console log the state the data is sorted probably as I want the only problem is that component doesn't re render after updating the state.

Also let me know if there is any other mistakes in the code, your help is highly appropriated.

 const Test = () => { const [state, setState] = useState([]); useEffect(() => { const fetchApi = async () => { setState(await fetchUsersData()) } fetchApi() },[setState]) const info = state.map((data, i) => { return (<div key={i}> <p >{data.users}</p> <p >{data.ages}</p> </div>) }) const sortByAge = () => state.sort((a, b) => { return a.age < b.age? 1: -1 }) const handleClick = () => { setState(sortByAge()) } return ( <div> <button onClick={handleClick}>Sort by Age</button> {info} </div> ); } export default Test;

Your issue is that you're mutating state when you do the sorting. Try doing a shallow copy when you apply the sort:

const sortByAge = () => [...state].sort((a, b) => {
  return a.age < b.age ? 1: -1
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM