0

我正在尝试在异步操作中使用 getState 函数。我正在使用 Typescript 和中间件 redux-thunk 在 React 中工作。我添加了带有 getState 的参数作为第二个参数,如下所示:

export const fetchPostsAndUsers = () => async (dispatch: ThunkDispatch<State, unknown, Action>, getState : () => State )  => {
    await dispatch(fetchPosts())
    const userIds: number[] = Array.from(new Set(getState().posts.map((post: Post) => post.userId)));
    userIds.forEach(id => dispatch(fetchUser(id)));
}

但是我在连接组件中输入此 getState 时遇到问题。往下看:

interface ConnectedProps {
    createStream: (formValues: IStream, getState? : () => State) => void,

}

const  StreamCreate = (props: InjectedFormProps<IStream, ConnectedProps> & ConnectedProps) => {

    const onSubmit = (formValues: IStream) => {
        props.createStream(formValues);
    }
    const classes = useStyles();
    return (
        (
            <Container maxWidth="sm">
                <form className={classes.root} style={{marginTop: '100px'}} onSubmit={props.handleSubmit(onSubmit)}>
                    <Field name="title" label="Enter Title" component={renderInput}/>
                    <Field name="description" label="Enter description" component={renderInput}/>
                    <Button variant="contained" color="primary" type="submit" style={{marginLeft: '10px'}}>
                        Submit
                    </Button>
                </form>
            </Container>
        )
    );
}

const formWrapped = reduxForm<IStream, ConnectedProps>({
    form: "streamCreate",   // name of using form
    validate
})(StreamCreate);


const mapDispatchToProps = (dispatch: Dispatch) => {
    return bindActionCreators({
            createStream,
        }, dispatch
    )
};

export default connect(null, mapDispatchToProps)(formWrapped);

错误在最后一行:

export default connect(null, mapDispatchToProps)(formWrapped);

就像在下面的屏幕上:

在此处输入图像描述

我怎样才能避免这个错误?在这种情况下,getState 函数的正确类型是什么?我将不胜感激。

4

1 回答 1

0

好的,对不起,这是我的错。我错误地通过了 getState。应该是返回函数:

export const createStream = (formValues: IStream) => {
    return async (dispatch: ThunkDispatch<void, State, Action>,  getState: () => State) => {
        const userId = getState().auth.userId;
        const response: AxiosResponse<Stream> = await streams.post<Stream>('/streams', {...formValues, userId});
        dispatch({type: ActionType.CREATE_STREAM, payload: response.data})
    }
}; 
于 2021-07-29T08:17:09.870 回答