簡體   English   中英

在 redux-thunk 異步操作中使用 getState

[英]Using getState in redux-thunk async action

我正在嘗試在異步操作中使用 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 函數的正確類型是什么? 我將不勝感激。

好吧,對不起這是我的錯。 我錯誤地通過了 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})
    }
}; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM