React 状态覆盖当前的 reducer

时间:2021-03-12 05:25:13

标签: reactjs redux react-hooks reducers

我有一个名为 Restaurante 的组件,我正在尝试从我的餐厅减速器调用操作 FETCH_ALL。我正在成功地从 MongoDB 中使用该信息。

为了获得这些信息,我使用了 useEffect 钩子,我在其中调用了操作 getRestaurantes()

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

我有另一个名为 RestauranteData 的组件,它是一个表格,显示使用 dispatchuseSelector 钩子获得的所有信息

const dispatch = useDispatch();
const restaurantes = useSelector((state) => state.restaurantes);

如您所见,信息已成功显示在表格中:

restaurants table

我需要调用另一个操作来从另一个名为 consecutitvos 的集合中获取信息。当用户创建新餐厅时,此集合包含允许我创建自定义 ID 的信息。为了获取该信息,我有一个名为 getConsecutivos 的操作。

useEffect(() => {
        dispatch(getConsecutivos());
    });

const selectedConsecutivo = useSelector((state) => !currentConsecutivo ? state.consecutivos.find((c) => c.type === "Restaurants") : null);

我遇到的问题是,当我调用该操作时,状态会覆盖,有时表格会显示 consecutitvos 信息而不是餐厅信息。如果我重新加载页面,表格中显示的信息会发生变化。

这是我在 Restaurante 组件中的完整代码

const Restaurante = () => {

    const [currentId, setCurrenteId] = useState(null);
    const [show, setShow] = useState(false);
    const dispatch = useDispatch();
    const [inputSearchTerm, setinputSearchTerm] = useState('');
    const [selectedTypeSearch, setSelectedTypeSearch] = useState('');
    const [inputSearchTermError, setinputSearchTermError] = useState('');
    const [currentConsecutivo, setCurrentConsecutivo] = useState(null);

    const reload=()=>{window.location.reload()};
   
    useEffect(() => {
        dispatch(getConsecutivos());
    });

   const selectedConsecutivo = useSelector((state) => !currentConsecutivo ? state.consecutivos.find((c) => c.tipo === "Restaurantes") : null);
   console.table(selectedConsecutivo);

    

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

RestauranteData 完整代码(渲染表格)

const RestauranteData = ({ setShow, currentId,  setCurrenteId, inputSearchTerm, selectedTypeSearch}) => {

    
    const dispatch = useDispatch();
    const restaurantes = useSelector((state) => state.restaurantes);

    console.log(restaurantes);

    return(
    
        <Table className="text-center" striped>
            <thead>
                <tr>
                    <th>Código</th>
                    <th>Nombre</th>
                    <th>Dirección</th>
                    <th>Cantidad de Clientes</th>
                    <th>Teléfono</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody className="text-white">
                {restaurantes.filter( restaurante => {

                    if(!inputSearchTerm){
                        return restaurante;

                    }else if( selectedTypeSearch === "codigo"){

                        if(restaurante.codigo.toLowerCase().includes(inputSearchTerm.toLowerCase())){

                            console.table(restaurante);
                            return restaurante;
                        }
                    }else if( selectedTypeSearch === "nombre"){

                        console.log(restaurante.descripcion);

                        if(restaurante.nombre.toLowerCase().includes(inputSearchTerm.toLowerCase())){
                            return restaurante;
                        }
                    }
                }).map( restaurante => {
        
                    return(
                        <tr key={restaurante._id}>
                            <td key={restaurante.codigo}>{restaurante.codigo}</td>
                            <td key={restaurante.nombre}>{restaurante.nombre}</td>
                            <td key={restaurante.direccion}>{restaurante.direccion}</td>
                            <td key="2">2</td>
                            <td key={restaurante.telefono}>{restaurante.telefono}</td>
                            <td>
                                <Button variant="outline-light" className="btn-action" onClick={() => {setCurrenteId(restaurante._id); setShow(true)}} ><FontAwesomeIcon icon={faPen}></FontAwesomeIcon></Button>
                                <Button variant="outline-light" className="btn-action" onClick={() => dispatch(deleteRestaurante(restaurante._id))}><FontAwesomeIcon icon={faTrash}></FontAwesomeIcon></Button>
                            </td>
                        </tr>
                    )
                })}
            </tbody>
        </Table>
        
    );
}

export default RestauranteData; 

restaurantes.js 减速器代码

const reducer = (restaurantes = [], action) => {
    switch (action.type) {
        case 'DELETE':
            return restaurantes.filter((restaurante) => restaurante._id !== action.payload); //keep all the restaurantes but the action.payload
        case 'UPDATE':
            return restaurantes.map((restaurante) => restaurante._id === action.payload.id ? action.payload : restaurante);
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...restaurantes, action.payload];
    
        default:
            return restaurantes;
    }
}

export default reducer; 

consecutivos.js 减速器代码

const reducer = (consecutivos = [], action) => {
    switch (action.type) {
        case 'DELETE':
            return consecutivos.filter((consecutivo) => consecutivo._id !== action.payload); //keep all the consecutivos but the action.payload
        case 'UPDATE':
            return consecutivos.map((consecutivo) => consecutivo._id === action.payload.id ? action.payload : consecutivo);
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...consecutivos, action.payload];
    
        default:
            return consecutivos;
    }
}

export default reducer; 

index.js 组合减速器

import { combineReducers } from 'redux';
import consecutivos from './consecutivos';
import restaurantes from './restaurantes';


export default combineReducers({ consecutivos, restaurantes });

应用的index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'; //Keep track of the Store
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';

import App from './App';

const store = createStore(reducers, compose(applyMiddleware(thunk)));


ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root')
);

1 个答案:

答案 0 :(得分:1)

在你的reducer函数中,你将使用不同的动作类型名称而不是使用相同的名称,并且在你的动作方法中也改变动作类型名称

find
相关问题