Bro*_*ock 1 javascript reactjs redux redux-thunk react-hooks
我正在学习 Redux,我对这里发生的事情感到非常困惑。我正在使用 thunk 并且 GET_ITEMS 在我的减速器中,所以我不确定我做错了什么?错误在dispatch(getItemsAction());
Redux.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 });
});
},
});
Run Code Online (Sandbox Code Playgroud)
购物清单.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());
}, []);
Run Code Online (Sandbox Code Playgroud)
在最上面的代码中,您以不正确的方式返回了调度,但实际上您需要像 cb 一样调用调度,例如在 javascript 中我们做这样的事情
const myfunc = () => cb => {
cb('OK')
};
Run Code Online (Sandbox Code Playgroud)
它在javascript中的回调,你必须像回调一样返回调度才能正常工作
export const getItemsAction = () => dispatch => {
axios.get('api/items').then(response => {
dispatch({
type: 'GET_ITEMS',
payload: response.data
})
});
};
Run Code Online (Sandbox Code Playgroud)
最后不要忘记使用response.data获取 axios 响应数据
| 归档时间: |
|
| 查看次数: |
490 次 |
| 最近记录: |