REDUX:错误:操作可能没有未定义的"type"属性。你拼错常量了吗?



我正在学习Redux,我对这里发生的事情感到非常困惑。我正在使用 thunk,GET_ITEMS在我的减速器中,所以我不确定我做错了什么?错误在dispatch(getItemsAction());

重新.js

function reducer(state, action) {
switch (action.type) {
case 'GET_ITEMS':
return {
...state,
items: action.payload,
loading: false,
};
case 'ADD_ITEM':
return {
...state,
items: [...state.items, action.payload],
};
case 'DELETE_ITEM':
return {
...state,
items: state.items.filter(item => item.id !== action.payload),
};
case 'ITEMS_LOADING':
return {
...this.state,
loading: true,
};
default:
return state;
}
}
export const getItemsAction = () => ({
return(dispatch) {
axios.get('api/items').then(response => {
console.log(response);
dispatch({ type: 'GET_ITEMS', payload: response.data });
});
},
});

购物清单.js

import { addItemAction, deleteItemAction, getItemsAction } from '../redux';
export default function ShoppingList() {
const items = useSelector(state => state.items);
const dispatch = useDispatch();
const addItem = name => dispatch(addItemAction(name));
const deleteItem = id => dispatch(deleteItemAction(id));
useEffect(() => {
dispatch(getItemsAction());
}, []);

在顶部代码中,您以不正确的方式返回了调度 但实际上你需要像 CB 一样调用调度 例如,在JavaScript中,我们做这样的事情

const myfunc = () => cb => {
cb('OK')
};

它在 JavaScript 中的回调,您必须像回调一样返回调度才能正常工作

export const getItemsAction = () => dispatch => {
axios.get('api/items').then(response => {
dispatch({
type: 'GET_ITEMS',
payload: response.data
})
});
};

最后不要忘记使用响应获取Axios 响应数据

该操作的正确语法是

export const getItemsAction = () => dispatch => {
axios.get('/api/items').then(res =>
dispatch({
type: 'GET_ITEMS',
payload: res.data,
})
);
};

最新更新