简体   繁体   English

为什么在按钮单击时没有反应重新渲染页面?

[英]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.

相关问题 在 ReactJS (preact) 中单击按钮时状态更改后,React 不会重新渲染 - React doesn't re-render after State change on button click in ReactJS (preact) backgroundColor 不会重新渲染 - React - backgroundColor doesn't re-render - React 点亮:简单的按钮单击更改反应属性不会导致重新渲染 - lit: simple button click changing reactive property doesn't cause a re-render 响应上下文变量更改时,页面不会重新呈现 - Page doesn't re-render when react context variable changes 从 react-dom 导航不会重新呈现整个页面 - Navigate from react-dom doesn't re-render the entire page 为什么更改 state 时我的功能组件没有重新渲染? (反应) - Why my functional component doesn't re-render when change state? (react) MeteorJS-为什么数据更改后我的页面没有重新呈现? - MeteorJS - Why is my page doesn't re-render when the data changed? React js,为什么在更改open的值时我的组件不重新渲染? - React js, why doesn't my component re-render when I change the value of open? 为什么这个 React 组件在其 prop 更改时不重新渲染? - Why doesn't this React component re-render when its prop changes? 为什么 useContext 不重新渲染组件 - React.js + Laravel - Why useContext doesn't re-render the component - React.js + Laravel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM