将对象传递给Redux React进行更改

11 浏览
0 Comments

将对象传递给Redux React进行更改

此问题已经在此处有答案

如何在React中更新嵌套状态属性

我想编写一个函数,在接收到一个元素后,我想要改变其中的某个值,然后更新过滤器。我不知道如何在对象过滤器中得到这个特定元素,因为我传递的是对象本身,没有任何“id”。

mapActions.js

export const setFilters = (el, old_filters) => {
    console.log(el)
    const filters = {
        ...old_filters,
        [el]: { 
          ...old_filters[el],
          active: !old_filters[el].active
        }
      };
    return (dispatch, getState) => {
        dispatch({
            type: actions.SET_FILTERS,
            filters: filters
        })
    }
}

FilersObject.js

    changeFilterHandler = (el, i) => {
        this.props.setFilters(el, this.props.filters);
    }
[..]
            {Object.keys(this.props.filters).map(x => this.props.filters[x]).map((el, i)=> {
                return(
                     (this.changeFilterHandler(el))}
                        />
                )
            })}

一切都运作正常,但我不知道如何在mapActions.js中的函数setFilters()中,通过改变变量\'active\'来交换适当的对象

console.log(el)的输出是:

\"enter

我得到的错误是:

TypeError: Cannot read property 'active' of undefined

状态:

const initState = {
    filters: {
        basen: {
            active: true,
            name: 'BASEN'
        },
        koszykowka: {
            active: true,
            name: 'KOSZYKÓWKA'
        },
        pilka_nozna: {
            active: true,
            name: 'PIŁKA NOŻNA'
        }
    }}

admin 更改状态以发布 2023年5月21日
0
0 Comments

您当前的代码似乎会改变您在setFilters中的old_filters。相反,确保仅更改您创建的新对象。

以下是一种相当常见的模式,将您的状态树向下浅复制到需要更改变量的点。

export const setFilters = (el, old_filters) => {
  const filters = {
    ...old_filters,
    [el]: { 
      ...old_filters[el],
      active: !old_filters[el].active
    }
  };
  return (dispatch, getState) => {
    dispatch({
      type: actions.SET_FILTERS,
      filters: filters
    })
  }
}

编辑:将筛选器键传递给更改处理程序而不是对象值将很有益:

{Object.entries(this.props.filters).map(([key, el])=> {
  return(
     (this.changeFilterHandler(key))}
    />
  )
})}

0