typescript - 如何定义redux thunk函数的mapDispatchToProps类型
问题描述
按照官方文档,我制作了一个类似 thunk 功能的登录打字稿。
function loginApi(user: UserState) {
return fetch(
`${baseUrl}/login?user=${user.userName}&pwd=${user.pwd}`
)
.then(res => res.json())
}
export const thunkLogin = (
user: UserState
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
const asyncResp = await loginApi(user)
dispatch(
updateUser({
loggedIn: asyncResp.isloggedIn,
userName: user.userName,
userPwd: user.userPwd
})
)
}
我想使用 react-redux connect hoc 函数将此 thunk 函数添加到我的应用程序组件中。
import { thunkLogin } from './thunkLoginPath'
interface Props {
// place 1
thunkLogin: typeof thunkLogin
}
interface State {
userName: string
userPwd: string
}
class AppComponent extends React.Component<Props, State> {
handleSubmit = () => {
this.props.thunkLogin({
userName: this.state.userName,
userPwd: this.state.userPwd
})
}
render(){
return(
<TouchableOpacity
style={style.loginBotton}
onPress={this.handleSubmit}
>
<Text style={style.loginBottomText}>LOGIN</Text>
</TouchableOpacity>
)
}
}
export default connect(
(state: AppState) => ({
user: state.user
}),
// place 2
{ thunkLogin }
)(AppComponent)
它报告一个错误表明 thunkLogin 在 Props 声明不能分配给 mapDispatchToProps (place 1 -> place 2)。
解决方案
您是要连接 AppComponent 还是 Login 组件,因为您尝试从 AppComponent 调用 this.props.thunkLogin 但您连接了 Login。尝试像这样改变它。
export default connect(
(state: AppState) => ({
user: state.user
}),
// place 2
{ thunkLogin }
)(AppComponent)
推荐阅读
- http - 在 web.xml 中阻止不需要的 HttpMethods
- c# - Cinchoo ETL 将 Class 序列化为 csv
- mysql - 优化 SQL 计数
- php - 查询使用变量,但我不知道为什么,你能帮帮我吗?
- python - Pyhton3 - 发送电子邮件失败 - “OSError: [Errno 113] No route to host”
- ios - iOS BLE 中心如何在通知模式下从外围设备接收超过 182 个字节?
- sas - 如何将 SAS 宏与 %DO 和 %IF 一起使用
- nuxt.js - cursor.buffer.readInt32LE 不是函数
- c++ - 链表上的 MergeSort - 出现分段错误
- security - 云存储公司如何检查恶意内容?