⚛️ 기본 환경: IDE: VS code, Language: React
발생 Error
React에서 다음 Source Code를 실행할 경우,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import classes from './CartButton.module.css';
import uiActions from '../../store/ui-slice'
import { useDispatch } from 'react-redux';
const CartButton = (props) => {
const dispatch = useDispatch();
const toggleCartHandler = () => {
dispatch(uiActions.toggle());
};
return (
<button className={classes.button} onClick={toggleCartHandler}>
<span>My Cart</span>
<span className={classes.badge}>1</span>
</button>
);
};
export default CartButton;
|
🚨 toggleCartHandler가 onClick 메서드로 걸린 버튼 클릭 시, 다음과 같은 오류 발생
TypeError: _store_ui_slice__WEBPACK_IMPORTED_MODULE_1__.default.toggle is not a function
발생 원인
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import { createSlice } from "@reduxjs/toolkit";
const uiSlice = createSlice({
name: 'ui',
initialState: {cartIsVisible: false},
reducers: {
toggle(state){
state.cartIsVisible = !state.cartIsVisible;
}
},
});
export const uiActions = uiSlice.actions;
export default uiSlice;
|
uiSlice를 default로 export, uiActions는 개별 함수로 export
default로 export하지 않은 uiActions를 {}없이 import
해결 방법
⭐ export default로 내보낸 것만 중괄호 없이 import
이 외export 문은 중괄호를 사용하여 import
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import classes from './CartButton.module.css';
import {uiActions} from '../../store/ui-slice'
import { useDispatch } from 'react-redux';
const CartButton = (props) => {
const dispatch = useDispatch();
const toggleCartHandler = () => {
dispatch(uiActions.toggle());
};
return (
<button className={classes.button} onClick={toggleCartHandler}>
<span>My Cart</span>
<span className={classes.badge}>1</span>
</button>
);
};
export default CartButton;
|
'JavaScript > React with Error' 카테고리의 다른 글
[해결 방법] could not find react-redux context value; (0) | 2023.06.05 |
---|---|
[해결 방법] Actions must be plain objects. Use custom middleware for async actions. (0) | 2023.06.05 |
[해결 방법] "reduxjs": Unknown word. cSpell (0) | 2023.06.04 |
[해결 방법] export 'default' (imported as 'redux') was not found in 'redux' (0) | 2023.06.04 |
[해결 방법] React Hook "useState" cannot be called inside a callback 2 (0) | 2023.06.03 |