简体   繁体   English

反应 map function 停止工作 state 更新

[英]React map function stop working on state update

I'm trying to make an update on an Object that is in the state using React Hooks, but when I try to update the Objet the function .map stop working. I'm trying to make an update on an Object that is in the state using React Hooks, but when I try to update the Objet the function .map stop working.

First I have this handleCheckedFilterChange function and it change the state Object but the component was not re-render:首先我有这个handleCheckedFilterChange function 并且它改变了 state Object 但组件没有重新渲染:

const handleCheckedFilterChange = (name) => {
    let prevFilters = filters;
    for (let filter in prevFilters) {
      if (prevFilters[filter].name === name) {
        prevFilters[filter].checked = !prevFilters[filter].checked;
        prevFilters[filter].filters.map((value) => {
          value.disabled = !value.disabled;
        });
        setFilters(prevFilters);
        break;
      }
    }
};

So then I change it to this one to make the component render again:然后我将其更改为这个以使组件再次呈现:

const handleCheckedFilterChange = (name) => {
    let prevFilters = { ...filters };
    for (let filter in prevFilters) {
      if (prevFilters[filter].name === name) {
        prevFilters[filter].checked = !prevFilters[filter].checked;
        prevFilters[filter].filters.map((value) => {
          value.disabled = !value.disabled;
        });
        setFilters(prevFilters);
        break;
      }
    }
};

But this second one generates me an error:但是第二个给我一个错误:

TypeError: filters.map is not a function类型错误:过滤器。map 不是 function

The error is when I call the following:错误是当我调用以下内容时:

const renderCards = filters.map((filter) => (
    <div className="card text-center">
      ...
    </div>
));

In the first option you are trying to modify the state directly which is not allowed in React's useState and that's why it is not rendering your expected change.在第一个选项中,您尝试直接修改 state,这在 React 的useState中是不允许的,这就是为什么它没有呈现您预期的更改的原因。

The problem with the second option is your are trying to use {} instead of [] .第二个选项的问题是您尝试使用{}而不是[] Try as:尝试如下:

let prevFilters = [ ...filters ];

The reason behind is .map() is a function on arrays and not on objects.背后的原因是.map()是 arrays 上的 function 而不是对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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