反应删除项目和更新列表

时间:2021-01-03 18:52:09

标签: reactjs redux

我正在为我的应用程序使用 react redux。我有产品列表,它具有功能:

React.useEffect(() => {
        dispatch(productsActions.fetchProducts(categoryId, sortBy, searchValue));
    }, [dispatch, categoryId, sortBy, searchValue]);

当我使用此功能删除产品时:

 const deleteProduct = React.useCallback((productId) => {
        dispatch(productsActions.deleteProduct(productId));
    }, [dispatch]);

我需要更新我的页面才能看到该产品已被删除。

如何在不更新页面的情况下更好地更新产品列表?

这是产品页面的所有代码:

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Header } from '../components/Header';
import { LeftMenu } from '../components/LeftMenu';
import * as productsActions from '../store/actions/products';
import { Link } from 'react-router-dom';

export const Products = () => {

    const dispatch = useDispatch();
    const [searchValue, setSearchValue] = React.useState('');
    const [isRefreshing, setIsRefreshing] = React.useState(false);
    const [isLoading, setIsLoading] = React.useState(false);
    const products = useSelector(state => state.products.products);
    const categoryId = undefined;
    const sortBy = undefined;

    React.useEffect(() => {
        dispatch(productsActions.fetchProducts(categoryId, sortBy, searchValue));
    }, [dispatch, categoryId, sortBy, searchValue]);

    const deleteProduct = React.useCallback((productId) => {
        dispatch(productsActions.deleteProduct(productId));
    }, [dispatch]);

    return (
        <div class="wrapper">
            <Header />
            <article class="main">
                <div class="row">
                    <div class="search-bar">
                        <input name="search" searchData={searchValue} onChange={e => setSearchValue(e.target.value)} value={searchValue} className="searchOpen" placeholder="Search products..." />
                        <Link class="add-button" to="add-product">Add product</Link>
                    </div>
                </div>
                <div class="row">
                    <div class="item--4-4">
                        <div class="item-title">
                            <table>
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Image</th>
                                        <th>Title</th>
                                        <th>Category</th>
                                        <th>Price</th>
                                        <th>Status</th>
                                        <th></th>
                                    </tr>

                                </thead>
                                <tbody>
                                    {products.map(product => (
                                        <tr>
                                            <td><a href="#">{product._id}</a></td>
                                            <td><a href="#"><img class="product-image" src={product.imageUrl} /></a></td>
                                            <td><a href="#">{product.title}</a></td>
                                            <td>{product.category.title}</td>
                                            <td>{product.price}</td>
                                            <td><span class="status">{product.status}</span></td>
                                            <td><button onClick={() => deleteProduct(product._id)}><ion-icon name="close-outline"></ion-icon>
                                            </button>
                                                <button><ion-icon name="create-outline"></ion-icon></button></td>
                                        </tr>
                                    )
                                    )}

                                </tbody>
                            </table>

                        </div>
                        <div class="pagination">
                            <p class="pagination-label">1-10 of 10</p>
                            <a href="#">
                                <ion-icon name="chevron-back-outline"></ion-icon>
                            </a>
                            <a href="#">
                                <ion-icon name="chevron-forward-outline"></ion-icon>
                            </a>

                        </div>
                    </div>

                </div>

            </article>
            <LeftMenu />
        </div>
    )
}

这是我对产品的操作:

import axios from 'axios';
import Product from '../../models/product';

export const FETCH_PRODUCTS = 'FETCH_PRODUCTS';
export const ADD_PRODUCT = 'ADD_PRODUCT';
export const DELETE_PRODUCT = 'DELETE_PRODUCT';

export const fetchProducts = (categoryId, sortBy, title) => {
    return async dispatch => {
        try {
            const response = await axios({ method: 'post', url: 'http://localhost:3000/api/products', data: { categoryId, sortBy, title } });
            const resData = await response.data.products;
            const loadedProducts = [];
            for (const key in resData) {
                loadedProducts.push(new Product(
                    resData[key]._id,
                    resData[key].title,
                    resData[key].imageUrl,
                    resData[key].description,
                    resData[key].price,
                    resData[key].status,
                    resData[key].categoryId,
                ))
            }
            dispatch({ type: FETCH_PRODUCTS, products: loadedProducts });
        } catch (error) {
            throw error;
        }
    }
}

export const addProduct = (product) => {
    return async dispatch => {
        const response = await axios({ method: 'post', url: 'http://localhost:3000/api/add-product', data: { product } });
        const resData = await response.data;
        dispatch({
            type: ADD_PRODUCT,
            product: resData
        });
    };
};

export const deleteProduct = (productId) => {
    return async dispatch => {
        const response = await axios({ method: 'post', url: 'http://localhost:3000/api/delete-product', data: { productId } });
        console.log('RESPO:', response)
        const resData = await response.data;
        dispatch({
            type: DELETE_PRODUCT,
            product: resData
        });
    };
};

这是我的产品减速器:

import {
    FETCH_PRODUCTS,
    ADD_PRODUCT,
    DELETE_PRODUCT
} from '../actions/products';

const initialState = {
    products: [],
    loading: true
};

export default (state = initialState, action) => {
    switch (action.type) {
        case FETCH_PRODUCTS:

            return {
                ...state,
                products: action.products,
                loading: false
            }
        case ADD_PRODUCT:

            return {
                ...state,
                products: action.product
            }
        case DELETE_PRODUCT:

            return {
                ...state,
                products: action.product
            }
    }
    return state;
}

1 个答案:

答案 0 :(得分:0)

我认为这对其他人有帮助。 我在删除产品时忘记更新我的减速器中的状态。

因此,在产品减速器中应该过滤当前状态,从状态中删除已删除的产品:

case DELETE_PRODUCT:

            const upds = state.products.filter(items => {
                return items._id !== action.productId;
            });

            return {
                ...state,
                products: upds
            }