繁体   English   中英

如何从我的 redux 存储中删除数组?

[英]How can I remove an array from my redux store?

我正在努力删除一个数组。 但它不工作。 删除后我的数组长度和数据保持不变。

这是我的前端反应网页

renderAdmin = (id) => {
        
        if(this.props.auth.user.userType==='normal') return(<td></td>);
        return (
        <React.Fragment>
            <td>
                <button onClick={() => this.props.changeStatus(id)}
                className="ui button" >Change Status</button>
            </td>
            <td>
                <button onClick={() => this.props.deleteUser(id)}
                className="ui button" >Delete User</button>
            </td>
        </React.Fragment>
        );
    }

在这里,我正在获取我的数组的 id。

现在这是我的 redux 动作创建者

export const deleteUser = (id) =>  (dispatch,getState) => {
  const user = JSON.parse(localStorage.getItem('user'));

  axios.delete(`/api/users/remove/${id}`, {
    headers: {
      'Authorization': `${user.token}`
    }
  }).then((res) => {
    console.log(res.data);
  
    dispatch({
      type: 'DELETE_USER',
      payload: res.data
  })

  dispatch({
      type: 'CREATE_ERROR',
      payload: 'User Delete'
  })
    
  })
  .catch((error) => {
    console.error(error)
  })
}

首先,我从后端服务器中删除它。 这很好用。 然后我将 res.data 发送到我的减速器负载。 DELETE_USER 工作不正常。 但 CREATE_ERROR 工作正常。

这是我的减速机

export default function (state = [] , action) {
    //  console.log(action)
      switch(action.type) {
          case 'ALL_USER' : return action.payload;  
          case 'EDIT_USER' :    
            return state.map(user=>{
                if(user._id === action.payload._id){
                    return action.payload;
                }
                else {
                    return user;
                }
            });
          case 'DELETE_USER' :
            return state.filter(user=>
                user !== action.payload
            )
          default : return state;
      }
  }

按删除按钮后,数据从服务器中删除,但 redux 存储始终保持不变。 请帮我。 谢谢你。

这可能是由于对象不是真正相等的,而是尝试过滤 id:

return state.filter(user=>
                user._id !== action.payload._id
            )

或者检查深度相等。

暂无
暂无

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

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