javascript - UseReducer 的 dispatch 函數拋出意外錯誤:預期 0 個參數,但收到 1 個
找不到任何相關的答案,唯一的相關內容是直接與 Redux 相關,因此提出一個對你們中的某些人來說可能很明顯的問題。就我的程式碼而言,看起來一切都是正確的,但我仍然遇到以下錯誤:預期 0 個參數,但獲得 1 個
程式碼:
// An enum with all the types of actions to use in our reducer
enum ActionType {
INCREASE = 'INCREASE',
}
// An interface for our actions
interface Action {
types: ActionType;
payload: number;
}
// An interface for our state
interface allState {
playersNumber: number,
playerData: string
}
const reducer : any = (state : allState, action : Action) => {
switch (action.types) {
case ActionType.INCREASE:
return { playersNumber: state.playersNumber + 5}
}
}
const initialState = {
playersNumber : 0,
playerData: ""
}
const App : FC<any> = () => {
const [responseData , setResponseData] = useState<Array<object>>([]);
const [state, dispatch] = useReducer(reducer, initialState);
// Fetching data with Axios
const fetchingData = async () => {
const response = await axios.get<Array<object>>('http://localhost:3006/lfy');
setResponseData(response.data);
console.log(response.data.length);
dispatch({type: ActionType.INCREASE})
}
useEffect(() => {
fetchingData();
}, []);
return (
<Routes>
{console.log(state)}
<Route path="/" element={<Home />} />
</Routes>
);
}
export default App;答案#1
你已經相當接近了!只需要修正幾個小地方。首先,你需要從 reducer 中移除 any 類型,並且總是返回函數內的整個 state:
const reducer = (state : allState, action : Action) => {
switch (action.types) {
case ActionType.INCREASE:
return {...state, playersNumber: state.playersNumber + 5}; // use the shallow copy for the state so you make sure to not replace it completely
default:
return state;
}
}
最終,當你呼叫 dispatch 時,你寫的是 type 而不是 types,而且你也沒有傳遞 payload。如果 payload 是可選的,你必須在介面中將其設為可選:
interface Action {
types: ActionType;
payload?: number; // note the question mark
}
dispatch({types: ActionType.INCREASE});
