我在 React 和 Typescript 中有一个功能组件。我正在使用 redux 和 redux thunk。我有一个用于登录用户的表单,它向我的 API 发送请求。我的表单工作正常,状态正在更新,但组件在状态更改时不会重新呈现。让我们来看看代码。
商店:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { authReducer } from './reducers/users';
const reducer = combineReducers({
auth: authReducer,
});
const initialState = {};
const middleware = [thunk];
const store = createStore(reducer, initialState, composeWithDevTools(applyMiddleware(...middleware)));
export default store;
减速器:
import { USER_LOGOUT, USER_SIGNIN, USER_SIGNUP } from '../constants/user';
import { IAction } from '../interfaces/global';
export const authReducer = (state = {}, action: IAction) => {
switch (action.type) {
case USER_SIGNUP:
return Object.assign(action.payload);
case USER_SIGNIN:
return { ...action.payload, test: 'A' };
case USER_LOGOUT:
return state;
default:
return state;
}
};
操作:
export const signin = (data: { email: string; password: string }) => async (dispatch: Function) => {
try {
const { data: auth }: AxiosResponse<IResponseSuccess> = await axios.post(`${process.env.REACT_APP_SERVER_URL}/api/users/signin`, data);
dispatch({
type: USER_SIGNIN,
payload: { ...auth.data },
});
} catch (error) {
dispatch({
type: USER_SIGNIN,
payload: { error: error.response.data.error },
});
}
};
最后,我在哪里发送动作:
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
// Some Validation for form which is ommited
// Dispatch
dispatch(signin(formData));
};
过去几个小时我一直在努力,希望得到任何帮助/提示。提前致谢。