redux 如何从reducer中获取对象的初始状态数组

mzsu5hc0  于 2022-11-12  发布在  其他
关注(0)|答案(3)|浏览(149)

我在访问redux对象的initialstates数组时遇到问题。
我有这样的初始状态:

export const initialState = [
  {
    blogPosts: [
      {
        title: "",
        category: "",
        logo: "",
        author: "",
        date: "",
        timeToRead: "",
        blogImage: "",
      },
    ],
  },
  { filterStatus: "" },
  { filterBy: "" },
];

我只想从我的reducer中修改filterStatus,但是这样做的同时也在数组中添加了一个对象。
我试着用我的减速器输入这个代码:

case SEARCH_AUTHOR:
      return [
        ...state,   
        (state[1].filterStatus = "author"),

      ];

我怎样才能改变摆脱这个毛病呢?

n3schb8v

n3schb8v1#

您在这里做什么:

case SEARCH_AUTHOR:
  return [
    ...state,   
    (state[1].filterStatus = "author"),
];

使用state-(...state)的整体创建一个新对象,然后修改第二项的筛选器状态,但只返回表达式的结果,即新设置的值"author"
有很多方法可以实现你想要的,我认为最简单的方法是复制数组,然后在返回之前修改副本。

case SEARCH_AUTHOR:
  const copy = [...state]
  copy[1] = {...copy[1], filterStatus: 'author'}
  return copy;

它的作用是:
1.创建数组的浅层副本-这会将相同的对象引用复制到新数组
1.用一个新对象覆盖索引1处的项,该对象扩展(复制)原始对象,然后覆盖所需的键
另一种可能的解决方案是在数组上使用mapreduce,并返回修改后的新数组,或者splice返回正确索引处的新对象

ccrfmcuu

ccrfmcuu2#

您可以使用splice state.splice(1, 1, { filterStatus: "author" }来移除{ filterStatus: "" },并改为设定{ filterStatus: "author" },然后传回return [...state]的状态复本。

const initialState = [
    {
      blogPosts: [
        {
          title: "",
          category: "",
          logo: "",
          author: "",
          date: "",
          timeToRead: "",
          blogImage: "",
        },
      ],
    },
    { filterStatus: "" },
    { filterBy: "" },
  ];

  const changeFilter = () => {
    initialState.splice(1, 1, { filterStatus: "author" } )
    return [ ...initialState ];
  }

  console.log(changeFilter())
f1tvaqid

f1tvaqid3#

使用var代替const

export var initialState = [
 {
  blogPosts: [
    {
    title: "",
    category: "",
    logo: "",
    author: "",
    date: "",
    timeToRead: "",
    blogImage: "",
    },
    ],
  },
    { filterStatus: "" },
    { filterBy: "" },
 ];

相关问题