[英]Why doesn't react re-render the page on button click?
function App() {
const [users,setUsers] = useState([])
useAsyncEffect(async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const data = await res.json()
setUsers(data)
}, [])
console.log(users)
function sortCity () {
users.sort((x,y) => {
if(x.address.city < y.address.city) {return -1}
if(x.address.city > y.address.city) {return 1}
return 0
})
console.log(users)
}
function sortCompany () {
users.sort((x,y) => {
if(x.company.name < y.company.name) {return -1}
if(x.company.name > y.company.name) {return 1}
return 0
})
console.log(users)
}
The log is displayed in the console sorted array, but the page is not re-renderer.日志显示在控制台排序数组中,但页面不会重新渲染。
<SortButton button={sortCity} text="по городу" />
<SortButton button={sortCompany} text="по компании"/>
I think that the problem is in setState, but I don't understand how to implement it我认为问题出在 setState 中,但我不明白如何实现它
.sort
array method mutates the state and you should avoid this. .sort
数组方法会改变 state ,你应该避免这种情况。 You cannot mutate anything in React, because it is not able to re-render.你不能在 React 中改变任何东西,因为它不能重新渲染。 You should set the new state directly.您应该直接设置新的 state。
In your case you should create a new array, sort it, and set into your state:在您的情况下,您应该创建一个新数组,对其进行排序,然后设置到您的 state 中:
function sortCompany () {
const sortedUsers = [...users]
sortedUsers.sort((x,y) => {
if(x.company.name < y.company.name) {return -1}
if(x.company.name > y.company.name) {return 1}
return 0
})
setUsers(sortedUsers);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.