本文介绍了如何使用 thunk 在 react-redux 钩子中进行异步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习钩子.但我不明白如何正确使用异步调用.早些时候我使用

import * as actionQR from "../actions/qr";...函数 mapDispatchToProps(dispatch) {返回 {actionQR: bindActionCreators(actionQR, dispatch),}}

然后调用我的 this.props.actionQR.myFunc(),但是我应该用 useDispatch() 做什么?如果我只是打电话

import {foo} from "../actions/qr";...useDispatch(foo());

然后我的 foo() 不要 console.log(2)

export const foo = () =>{控制台日志(1);返回(调度)=>{控制台日志(2);}}

我正在使用 thunk

import createRootReducer from './reducers/index';...const store = createStore(createRootReducer, applyMiddleware(thunk));
解决方案

useDispatch() 钩子会返回一个对 dispatch 函数的引用,你不要传给它一个动作,你得到 dispatch 引用并将动作传递给它(dispatch).

所以基本上它应该是这样的:

const dispatch = useDispatch()调度(富())

您可以从 react-redux DOCS 中获取更多详细信息/p>

I starting to learn hooks. But i dont understand how right work with async call.Earlier i was use

import * as actionQR from "../actions/qr";
...
function mapDispatchToProps(dispatch) {
    return {
        actionQR: bindActionCreators(actionQR, dispatch),
    }
}

and after this call my this.props.actionQR.myFunc(), but what I should do with useDispatch()?if I just call

import {foo} from "../actions/qr";
...
useDispatch(foo());

then my foo() dont console.log(2)

export const foo = () => {
    console.log(1);
    return (dispatch) => {
        console.log(2);
      }
}

Im using thunk

import createRootReducer from './reducers/index';
...
const store = createStore(createRootReducer, applyMiddleware(thunk));
解决方案

The useDispatch() hook will return a reference to the dispatch function, you don't pass to it an action, you get the dispatch reference and pass to it (the dispatch) the action.

So basically it should look something like this:

const dispatch = useDispatch()
dispatch(foo())

You can get more details from the react-redux DOCS

这篇关于如何使用 thunk 在 react-redux 钩子中进行异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 20:45