在这种情况下,在减速器内部更新状态的更好方法是什么?

case DELETE_INTEREST:
    let deleteInterests = state.user.interests;
    let index = deleteInterests.findIndex(i => i == action.payload);
    deleteInterests.splice(index, 1);
    return { ...state, user: { ...state.user, interests: deleteInterests } };

ESLint不喜欢在减速机中的case块中使用let语句,因此:

eslint:无大小写声明-大小写中意外的词汇声明

推荐答案

ESLint不喜欢在

这是不鼓励的,因为它会导致变量的作用域超出当前的case.通过使用块,可以将变量的范围限制到该块.

使用{}创建带有大小写的块范围,如下所示:

case DELETE_INTEREST: {
    let .....
    return (...)
}

查看以下片段:

function withOutBraces() { 
  switch(1){
    case 1: 
      let a=10; 
      console.log('case 1', a); 
    case 2: 
      console.log('case 2', a)
  } 
}

function withBraces() { 
  switch(1){
    case 1: {
      let a=10; 
      console.log('case 1', a); 
    }
    case 2: {
      console.log('case 2', a)
    }
  } 
}

console.log('========First Case ============')
withOutBraces()
console.log('========Second Case ============')
withBraces();

要从数组中删除元素,请使用array.filter,因为splice将在原始数组中进行更改.这样写:

case DELETE_INTEREST:
    let deleteInterests = state.user.interests;
    let newData = deleteInterests.filter(i => i !== action.payload);
    return { ...state, user: { ...state.user, interests: newData } };

Reactjs相关问答推荐

useLazyQuery不会更新所有组件之间的数据

InfiniteScroll持续获取数据,直到超过最大更新深度

无法使用#13;或br将新行设置为文本区域'"&"<>

如何获取用户在 GooglePlacesAutocomplete 中输入的文本?

如何在React组件中自动更新图表数据?

UseEffect 似乎不适用于页面的首次渲染

如果我使用 formik,如何在嵌套对象中写入正确的值?

如何在Next.js应用程序中为路由[slug]生成.html文件?

为什么我会收到此错误:无法在我的react 包上读取 null 的属性(读取useState)?

Primereact 的日历组件在每个月 12 日之后使用非唯一键生成

如何使用样式化函数为 TextField 的输入组件设置样式

React v6 中的公共和私有路由

无法在 KeyDown 上调用 useCallback 函数

如何在不重新加载页面的情况下加载新添加的数据?

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

在表格中显示具有自定义声明的用户状态

如何在 v6.4 中将 Auth0 提供程序与新的 createBrowsereRouter 一起使用?

NextJs - 如何从站点 map 生成器中删除重复的 URL?

如何通过 Material Ui 设计将 Accordion 添加到您的 React 项目中?

如果两个组件在 React 中导入相同的 CSS 文件会发生什么?