在official doc之后,我使用打字稿制作了redux thunk函数。
// store/user/thunk.ts
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
})
)
}
正如官方文件所说,我发送了这样的操作,在这里没有问题。
// app.tsx
import { updateUser } from '../store/action'
interface Props {
updateUser: typeof updateUser
}
interface State {
userName: string
userPwd: string
}
class AppComponent extends React.Component<Props, State> {
handleSubmit = () => {
this.props.updateUser({
userName: this.state.userName,
userPwd: this.state.userPwd
})
}
render(){
return(
<TextInput
style={style.userTextInput}
value={this.state.userName}
onChangeText={(userName) => this.setState({ userName })}
placeholder="input userName"
/>
<TextInput
style={style.userTextInput}
value={this.state.userPwd}
placeholder="input user password"
secureTextEntry={true}
onChangeText={(userPwd) => this.setState({ userPwd })}
/>
<TouchableOpacity
style={style.loginBotton}
onPress={this.handleSubmit}
>
<Text style={style.loginBottomText}>LOGIN</Text>
</TouchableOpacity>
)
}
}
export default connect(
(state: AppState) => ({
user: state.user
}),
{ updateUser }
)(AppComponent)
updateUser是这样的简单动作。
// store/user/action.ts
import { UserState, UPDATE_USER } from './types'
export function updateUser(newUser: UserState) {
return {
type: UPDATE_USER,
payload: newUser
}
}
但是当我将updateUser
替换为thunkLogin
时,它会报告一条错误消息,表明它无法分配给道具。
...
interface Props {
thunkLogin: typeof thunkLogin
}
...
handleSubmit = () => {
this.props.thunkLogin({
userName: this.state.userName,
userPwd: this.state.userPwd
})
}
...
export default connect(
(state: AppState) => ({
user: state.user
}),
{ thunkLogin }
)(AppComponent)
更新 错误报告
Argument of type 'typeof AppComponent' is not assignable to parameter of type 'ComponentType<Matching<{ user: UserState; } & { thunkLogin: (user: UserState) => void; }, Props>>'.
Type 'typeof AppComponent' is not assignable to type 'ComponentClass<Matching<{ user: UserState; } & { thunkLogin: (user: UserState) => void; }, Props>, any>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'Matching<{ user: UserState; } & { thunkLogin: (user: UserState) => void; }, Props>' is not assignable to type 'Props'.
Types of property 'thunkLogin' are incompatible.
Type '(user: UserState) => void' is not assignable to type '(user: UserState) => ThunkAction<void, { user: UserState; login: LoginState; }, null, Action<string>>'.
Type 'void' is not assignable to type 'ThunkAction<void, { user: UserState; login: LoginState; }, null, Action<string>>'. [2345]