【发布时间】:2021-08-28 15:06:11
【问题描述】:
我的 authActions.tsx 文件如下所示:
import {
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAILURE
} from './types';
import axios from 'axios';
import { Dispatch } from 'react';
interface ILoginObject {
email: string,
password: string
}
interface ILoginDispatch {
type: string,
payload?: {
success? : boolean,
status?: number,
message?: string,
user?: {
id: string,
email: string
},
access_token?: string,
expires_in?: string
}
}
export const userLogin = (loginObject: ILoginObject) => async (dispatch: Dispatch<ILoginDispatch>): Promise<void> => {
dispatch({
type: LOGIN_REQUEST
});
const response = await axios.post(`/api/login`, loginObject);
if(response.data && response.data.access_token) {
dispatch({
type: LOGIN_SUCCESS,
payload: response.data
});
}
else {
dispatch({
type: LOGIN_FAILURE,
payload: response.data
});
}
}
我的 Login.tsx 文件如下所示:
import React from 'react';
import { connect } from 'react-redux';
import { userLogin } from '../store/actions/authActions';
interface IProps {
auth: {
payload?: {
success? : boolean,
status?: number,
message?: string,
user?: {
id: string,
email: string
},
access_token?: string,
expires_in?: string
}
}
}
interface IState {
email: string,
password: string
}
interface IEvent {
target: HTMLInputElement
}
class Login extends React.Component<IProps, IState> {
state: IState = {
email: "",
password: ""
}
onEmailChange = (e: IEvent): void => {
this.setState({
email: e.target.value
})
}
onPasswordChange = (e: IEvent): void => {
this.setState({
password: e.target.value
})
}
onSubmit = (): void => {
//
}
render(): JSX.Element {
return(
<React.Fragment>
<div>
<div>
Email
</div>
<div>
<input type="text" name="email" onChange={e => this.onEmailChange(e)} />
</div>
</div>
<div>
<div>
Password
</div>
<div>
<input type="password" name="password" onChange={e => this.onPasswordChange(e)} />
</div>
</div>
<div>
<button onClick={this.onSubmit}>Submit</button>
</div>
</React.Fragment>
)
}
}
const mapStateToProps = (state: IProps) => {
return {
auth: state.auth
};
}
export default connect(mapStateToProps, { userLogin })(Login);
现在,我想使用“onSubmit = () => {}”函数中的“登录”操作发布请求。在 JavaScript 中,这可以通过简单的编写来完成
return this.props.userLogin({email: this.state.email, password: this.state.password}).then(() => {
// Something
})
但由于是 TypeScript,所以上面的代码不起作用,需要提前定义“userLogin”函数。我尝试将“userLogin: () => void”添加到“IProps”界面,但我收到错误消息“属性 'then' 在类型 'void' 上不存在”以使用该函数并且代码不起作用.
谁能帮忙?
【问题讨论】:
-
帮自己一个忙,切换到功能组件。当然,这可以正确输入,但使用
useDispatch钩子会更容易。
标签: javascript reactjs typescript react-redux