转换为 redux 工具包并获得 "Unhandled Rejection (TypeError): state.push is not a function"
converting to redux tool kit and getting "Unhandled Rejection (TypeError): state.push is not a function"
我在将旧项目转换为 redux 工具包时遇到了“未处理的拒绝(TypeError):state.push 不是函数”错误。我还没有掌握 action/thunk 和 reducer 的不变性。警报有效,但随后出现错误消息。
import axios from 'axios';
import { setAlert } from '../alerts/alertSlice';
const slice = createSlice({
name: 'auth',
initialState: {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user: null,
},
reducers: {
registerSuccess: (state, action) => {
const { payload } = action.payload;
state.push({
payload,
isAuthenticated: true,
loading: false,
});
},
registerFail: (state, action) => {
localStorage.removeItem('token');
state.push({
token: null,
isAuthenticated: false,
loading: false,
user: null,
});
},
},
});
const { registerSuccess, registerFail } = slice.actions;
export default slice.reducer;
// Register User
export const register =
({ name, email, password }) =>
async (dispatch) => {
const config = {
headers: {
'comtent-Type': 'application/json',
},
};
const body = JSON.stringify({ name, email, password });
try {
const res = await axios.post('/api/users', body, config);
dispatch({
type: registerSuccess,
payload: res.data,
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch(registerFail());
}
};
.push
是一个数组函数,用于在数组末尾添加一个新项 - 你的状态不是数组。
您可能想按照
的方式做一些事情
state.token = null
state.isAuthenticated = false
state.loading = false
state.user = null
我在将旧项目转换为 redux 工具包时遇到了“未处理的拒绝(TypeError):state.push 不是函数”错误。我还没有掌握 action/thunk 和 reducer 的不变性。警报有效,但随后出现错误消息。
import axios from 'axios';
import { setAlert } from '../alerts/alertSlice';
const slice = createSlice({
name: 'auth',
initialState: {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user: null,
},
reducers: {
registerSuccess: (state, action) => {
const { payload } = action.payload;
state.push({
payload,
isAuthenticated: true,
loading: false,
});
},
registerFail: (state, action) => {
localStorage.removeItem('token');
state.push({
token: null,
isAuthenticated: false,
loading: false,
user: null,
});
},
},
});
const { registerSuccess, registerFail } = slice.actions;
export default slice.reducer;
// Register User
export const register =
({ name, email, password }) =>
async (dispatch) => {
const config = {
headers: {
'comtent-Type': 'application/json',
},
};
const body = JSON.stringify({ name, email, password });
try {
const res = await axios.post('/api/users', body, config);
dispatch({
type: registerSuccess,
payload: res.data,
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch(registerFail());
}
};
.push
是一个数组函数,用于在数组末尾添加一个新项 - 你的状态不是数组。
您可能想按照
的方式做一些事情 state.token = null
state.isAuthenticated = false
state.loading = false
state.user = null