简体   繁体   English

清除 Redux 中的数组 state

[英]Clearing an array state in Redux

How do I clear an array state in Redux?如何清除 Redux 中的数组 state? I have an initial state of an empty array, and things are being added.我有一个空数组的初始 state,并且正在添加内容。 I want to have an action that just clear it, I tried the following method but it gives me "Unexpected token" error about the "action.payload" I give to the CLEAR_THINGS action:我想要一个只是清除它的操作,我尝试了以下方法,但它给了我关于我给 CLEAR_THINGS 操作的“action.payload”的“意外令牌”错误:

export default (state=[], action) => {
switch (action.type) {
    case "RECEIVE_THING":
        return [
            ...state,
            action.payload
        ];
    case "CLEAR_THINGS":
        return {
            ...state,
            action.payload // payload here is []...
        };
    default:
        return state;
}}

It also throw the error if I just use [] instead of through action.payload.如果我只使用 [] 而不是通过 action.payload,它也会抛出错误。

export default (state=[], action) => {
switch (action.type) {
    case "RECEIVE_THING":
        return [
            ...state,
            action.payload
        ];
    case "CLEAR_THINGS":
        return [];
    default:
        return state;
}}

The RECEIVE_THING action uses object spread notation to return a state that is an array ( [] ) which contains the prior state ( [...state] ) and adds to that a new item ( [...state, action.payload] ). RECEIVE_THING操作使用对象扩展符号返回一个状态,该状态是一个数组 ( [] ),其中包含先前状态 ( [...state] ) 并添加一个新项目 ( [...state, action.payload] )。 The key/property name used for this new item is simply the next index of the array.用于这个新项目的键/属性名称只是数组的下一个索引。 It is, after all, an array.毕竟,它是一个数组。

In your code for CLEAR_THINGS you are creating an object ( {} ) that contains the old state (say it was ['item1'] ) and so it looks like { '0': 'item1' } .CLEAR_THINGS的代码中,您正在创建一个包含旧状态的对象( {} )(假设它是['item1'] ),因此它看起来像{ '0': 'item1' } Next you proceed to use object shorthand notation to add more state, but this requires you use a single identifier (a single word) but you're using a dotted notion (qualified identifier) to access a property.接下来,您将继续使用对象速记符号来添加更多状态,但这需要您使用单个标识符(单个单词),但您正在使用虚线概念(限定标识符)来访问属性。 You're kind of instructing a property named action.payload be created but this is illegal and this is where your error comes from.您有点指示创建名为action.payload的属性,但这是非法的,这就是您的错误的来源。 The reason it works in the case of the array is because only a value is needed in this case, since the key is derived from the index of the array.它在数组的情况下工作的原因是因为在这种情况下只需要一个值,因为键是从数组的索引派生的。

What you want to do is always return the same kind of object, in your case, an array.您想要做的是始终返回相同类型的对象,在您的情况下,是一个数组。 By starting with return { , you're already going the wrong way.return {开始,你已经走错路了。

The ES6 shorthand for the operation ES6 操作的简写

{thing}

transpiles to转译为

{"thing": thing}

This causes a syntax error in your case because the key contains a period and it's unclear what the key should be.这会导致您的情况出现语法错误,因为密钥包含一个句点,并且不清楚密钥应该是什么。 Maybe you intend for something like this?也许你打算做这样的事情?

return {
    action: {
        payload: action.payload
    }
}

But this doesn't solve the problem at hand: if you want to clear the array with this action, you should not expand the existing state into the next state.但这并不能解决手头的问题:如果要使用此操作清除数组,则不应将现有状态扩展到下一个状态。 Instead you should just return something in the same shape as your existing state, but semantically has the meaning of empty (in this case, just an empty array).相反,您应该只返回与现有状态相同形状的东西,但在语义上具有空的含义(在这种情况下,只是一个空数组)。 I think what you want is我想你想要的是

case "RECEIVE_THING":
    return [
        ...state,
        action.payload
    ];
case "CLEAR_THINGS":
    return [];

You should just return and empty array in your "CLEAR_THINGS" handler:您应该在“CLEAR_THINGS”处理程序中返回并清空数组:

export default (state=[], action) => {
switch (action.type) {
    case "RECEIVE_THING":
        return [
            ...state,
            action.payload
        ];
    case "CLEAR_THINGS":
        return [];
    default:
        return state;
}}

Since you just want to clear everything there's not need to reference the existing state, you just want to set the new state to an empty array.由于您只想清除不需要引用现有状态的所有内容,因此您只想将新状态设置为空数组。

Another thing worth mentioning is that I'd probably nest my array in an object.另一件值得一提的事情是,我可能会将数组嵌套在一个对象中。 If your reducer gains more complexity in the future it'll be hard to add functionality this way as you have it and this approach would allow your app to gain further complexity if needed.如果您的减速器将来变得更加复杂,那么您将很难以这种方式添加功能,并且这种方法将使您的应用程序在需要时获得进一步的复杂性。 You can always add reducers of course, but I like making my reducers more flexible this way.当然,您可以随时添加减速器,但我喜欢通过这种方式使减速器更加灵活。 This would look like:这看起来像:

export default (state = { myArray: [] }, action) => {
switch (action.type) {
    case "RECEIVE_THING":
        return {
            ...state,
            myArray: state.myArray.concat([action.payload]),
        };
    case "CLEAR_THINGS":
        return {
            ...state,
            myArray: [],
        };
    default:
        return state;
}}

I wound up finding the answer here on another stackoverflow thread.彼时我找到了答案, 在这里上的另一个线程计算器。

The issue was because the function 'map' can only be used for arrays, not for objects.问题是因为函数“map”只能用于数组,不能用于对象。 So in my image component I had to change所以在我的图像组件中我不得不改变

this.props.filtered.map((pic)

to

this.props.filtered.filtered.map((pic)

I'm wanting to clear my state when my input has an empty value.当我的输入为空值时,我想清除我的 state。 How could I run a dispatch and it would erase my "data" state which contains all my data coming from the api?我怎样才能运行调度,它会删除我的“数据”state,其中包含来自 api 的所有数据?

This is my reducer:这是我的减速机:

export const SearchOpportunities = (state = initialState, action) => {
  console.log('action: ', action)

  switch (action.type) {
    case GET_SEARCH_OPPORTUNITIES_SUCCESS:
      return {
        ...state,
        data: [...state.data, action.payload],
        pagina: state.pagina + 1
      }
    case GET_ID_LICITACAO_SUCCESS:
      return {
        ...state,
        itens: [...state.itens, action.payload.data.itens]
      }
    case GET_SEARCH_OPPORTUNITIES_FAILED:
    case GET_ID_LICITACAO_FAILED:
      return {
        ...state,
        error: action.payload.data,
      }
    case CLEAR_LICITACOES:
    case CLEAR_ITENS:
      return {
        data: [],
        itens: []
      }
    default: 
      return state
  }
}

My index.js where I do my dispatch to get the data from the api:我在 index.js 中进行调度以从 api 获取数据:

const detectKeyPress = (e) => {
        const { key } = e;

        if (key === 'Enter') {
            try {
                dispatch({
                    type: GET_SEARCH_OPPORTUNITIES,
                    keyword: searchedWord,
                    pagina: data.pagina,
                })
            } catch (error) {
                dispatch(getSearchOpportunitiesFailed(error))
            }
        }
    }

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

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