【问题标题】:Update Nested Object in Array in React Using Redux使用 Redux 在 React 中更新数组中的嵌套对象
【发布时间】:2020-10-05 17:48:41
【问题描述】:

我正在尝试更改用户数组中的状态。我正在尝试将状态更新为“是”。我怎样才能在不改变状态的情况下访问其数据?

请查看此代码框链接

CLICK HERE

const dispatch = useDispatch();
  const isLoading = useSelector(state => state.user.isLoading);
  const users = useSelector(state => state.user.users);

  const onApprove = user => {
    dispatch(approveUser(user));
  };

  useEffect(() => {
    dispatch(getUsers());
  }, [dispatch]);

【问题讨论】:

    标签: javascript reactjs redux ecmascript-6 react-redux


    【解决方案1】:

    更新approveUser 操作以采取并传递user

    export function approveUser(user) { // <-- receive user object
      return dispatch => {
        dispatch({
          type: userConstants.APPROVE_USER_REQUEST
        });
        dispatch({
          type: userConstants.APPROVE_USER_SUCCESS,
          payload: {
            approved: "HAHAHHA"
          },
          user, // <-- pass user object
        });
        dispatch({
          type: userConstants.APPROVE_USER_FAILURE,
          payload: {}
        });
      };
    }
    

    然后更新 reducer 以传播更新。使用收到的 user 对象映射新的“是”状态。

    case userConstants.APPROVE_USER_SUCCESS:
      return {
        ...state,
        isLoading: false,
        users: state.users.map(user => user.id === action.user.id ? {
          ...user,
          status: 'yes',
        } : user)
      };
    

    【讨论】:

      【解决方案2】:

      要改变 reducer 中的状态而不改变,试试这个:

          case 'YOUR_ACTION':
              return {
                  ...state,
                  users: state.users.map((user) =>
                      user.id === action.userId
                          ? {
                                ...user,
                                status: 'yes', // or you could action.status
                            }
                          : user,
                  ),
              }
      

      我正在映射所有 users,然后将 user.id 与从操作发送的用户 ID 匹配,并将其状态更改为 yes。如果不匹配,我们只需返回user

      【讨论】:

      • 谢谢红男爵
      猜你喜欢
      • 2019-10-10
      • 2019-11-02
      • 2019-02-26
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 2019-08-03
      • 2023-01-23
      相关资源
      最近更新 更多