【发布时间】:2019-10-15 01:15:43
【问题描述】:
这应该很容易,但目前我无法解决,但我觉得这应该是一个简单的解决方法。我目前使用 redux 和 typescript 并使用 redux-thunk 异步操作创建者。
设置很简单。这是我用于登录的代码:
export function requestAuthenticationAsync(email: string, password: string) {
return (dispatch: ThunkDispatch<IState, undefined, IAction>): Promise<void> => {
dispatch(requestAuthentication());
return postAuthentication(email, password).then((response) => {
dispatch(receiveAuthentication());
return response.json();
}).then((data) => {
dispatch(receiveUser(data));
});
};
}
理想的情况是我可以在登录成功时使用.then 在.tsx 文件中调用它,以便在其他地方导航。
所以,当我在组件中执行类似操作时,它的工作原理与您期望的一样:
const { dispatch } = store;
dispatch(requestAuthenticationAsync('email', 'password')).then(() => {
// navigate somewhere
});
但是,当我像这样使用react-redux 中的connect 和mapDispatchToProps 时:
import './Gateway.scss';
import * as React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { requestAuthenticationAsync } from './actions';
import { withRouter } from 'react-router-dom';
const mapDispatchToProps = (dispatch) => {
return {
requestAuthenticationAsync: bindActionCreators(requestAuthenicationAsync, dispatch)
};
};
const mapStateToProps = (state) => {
return {
authenticated: state.authentication.authenticated
};
};
class Gateway extends React.Component<{
authenticated: boolean;
requestAuthenticationAsync: typeof requestAuthenticationAsync;
}, {
email: string;
password: string;
}> {
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
}
onGatewaySubmit = (event) => {
event.preventDefault();
const { requestAuthenticationAsync } = this.props;
const { email, password } = this.state;
requestAuthenticationAsync(email, password).then(() => {
console.log('done');
});
};
onEmailValueChange = (event) => {
this.setState({
email: event.target.value
});
};
onPasswordValueChange = (event) => {
this.setState({
password: event.target.value
});
};
render() {
return (
<div id='gateway'>
<form onSubmit={ this.onGatewaySubmit }>
<input
className='email'
onChange={ this.onEmailValueChange }
placeholder='email'
type='text' />
<input
className='password'
onChange={ this.onPasswordValueChange }
placeholder='password'
type='password' />
<input type='submit' value='Submit' />
</form>
</div>
);
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Gateway));
我收到以下错误:
TS2339: Property 'then' does not exist on type '(dispatch: ThunkDispatch<IState, undefined, IAction>) => Promise<void>'.
什么给了?在这种情况下如何让 TypeScript 满意,以便我可以使用带有 .then 的 Promise?
【问题讨论】:
标签: javascript reactjs typescript redux react-redux