【问题标题】:Using getState in redux-thunk async action在 redux-thunk 异步操作中使用 getState
【发布时间】:2021-10-04 21:29:45
【问题描述】:

我正在尝试在异步操作中使用 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 函数的正确类型是什么?我将不胜感激。

【问题讨论】:

    标签: reactjs typescript redux redux-thunk redux-async-actions


    【解决方案1】:

    好吧,对不起,这是我的错。我错误地通过了 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})
        }
    }; 
    

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 2017-03-03
      • 2018-09-15
      • 2020-01-17
      • 2016-12-20
      • 2020-02-22
      • 2019-12-17
      • 2016-09-19
      相关资源
      最近更新 更多