使用 UseState Hook 后 React 组件不会重新渲染 [英] React component not re-rendering after using UseState Hook
问题描述
我正在创建一个在屏幕上显示元素列表的 React 应用程序.我创建了一个函数,让用户可以按名称对元素进行排序.
I'm creating a react application that displays a list of elements on the screen. I created function that lets the user sort the elements by their name.
const [schools, setSchools] = useState([{title: element1}, {title: element2}, ...]);
const sortSchools = (key, value) => {
setSchools(schools.sort(compareValues(key, value)));
console.log(schools);
}
功能正常,改变学校状态;我可以从控制台看到这一点,但元素没有重新渲染.
The function is working properly, changing the schools' state; I can see that from the console, but the elements are not re-rendering.
我认为这是因为当值没有改变时,React 不会重新渲染组件,但自从顺序改变后,无法找到重新渲染元素的方法.
I think this is because React doesn't re-render components when the value hasn't changed, but can't figure out a way to re-render the elements since the order changed.
推荐答案
你需要传递一个新的实例给 setScholls 来让组件重新渲染,试试这个:
You need to pass a new instance to setScholls for the component to re-render, try this :
const sortSchools = (key, value) => {
setSchools([...schools.sort(compareValues(key, value))]);
console.log(schools);
}
这篇关于使用 UseState Hook 后 React 组件不会重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!