【发布时间】:2018-08-18 13:26:27
【问题描述】:
我正在尝试将代码从 Javascript React 重构为 Typescript React。
我在这里有一个动作,它执行一个 API 调用并返回一个带有 dispatch 的函数
我的UserActions.ts 文件看起来像这样
export const login = ({username, password}) => async (dispatch: any) => {
try {
let r = await apiCall(); //performing api call here
return r.code; //returning the custom responseCode here from my server
console.log(auth)
} catch (err) {
throw new Error(err);
}
}
在我的组件文件MyComponent.ts中有一个组件类的成员函数
public formSubmit = (e: React.FormEvent) => {
e.preventDefault();
const { password, email } = this.state;
this.props.login({
email,
password,
}).then(responseCode => {
//I want to access responseCode here
});
}
MyComponent.ts 中与 Redux 的连接如下所示
const mapStateToProps = (store: IAppState) => {
return {
}
}
export default connect(mapStateToProps, {
login
})(SignIn);
所以,如您所见,login 实际上返回了一个函数,该函数被传递到 Redux Thunk 中间件,然后在 this.props 中传递给 MyComponent
要从函数访问返回变量,我必须 type 登录操作中的外部函数 UserActions.ts。
那么我如何使用正确的类型进行访问?因为打字稿不允许我将this.props.login().then() 放入MyComponent.ts
【问题讨论】:
标签: reactjs typescript redux