如何使用 thunk 在 react-redux 挂钩中进行异步调用?
how to make async call in react-redux hooks with thunk?
我开始学习 hooks。但我不明白如何正确使用异步调用。
早些时候我使用
import * as actionQR from "../actions/qr";
...
function mapDispatchToProps(dispatch) {
return {
actionQR: bindActionCreators(actionQR, dispatch),
}
}
并在此调用我的 this.props.actionQR.myFunc()
之后,但我应该如何处理 useDispatch()?
如果我打电话给
import {foo} from "../actions/qr";
...
useDispatch(foo());
那我的foo()
不要console.log(2)
export const foo = () => {
console.log(1);
return (dispatch) => {
console.log(2);
}
}
我正在使用 thunk
import createRootReducer from './reducers/index';
...
const store = createStore(createRootReducer, applyMiddleware(thunk));
useDispatch()
钩子将 return 引用 dispatch
函数,你不传递给它一个动作,你得到 dispatch
引用并传递对它(dispatch
)采取行动。
所以基本上它应该看起来像这样:
const dispatch = useDispatch()
dispatch(foo())
您可以从 react-redux DOCS
中获取更多详细信息
我开始学习 hooks。但我不明白如何正确使用异步调用。 早些时候我使用
import * as actionQR from "../actions/qr";
...
function mapDispatchToProps(dispatch) {
return {
actionQR: bindActionCreators(actionQR, dispatch),
}
}
并在此调用我的 this.props.actionQR.myFunc()
之后,但我应该如何处理 useDispatch()?
如果我打电话给
import {foo} from "../actions/qr";
...
useDispatch(foo());
那我的foo()
不要console.log(2)
export const foo = () => {
console.log(1);
return (dispatch) => {
console.log(2);
}
}
我正在使用 thunk
import createRootReducer from './reducers/index';
...
const store = createStore(createRootReducer, applyMiddleware(thunk));
useDispatch()
钩子将 return 引用 dispatch
函数,你不传递给它一个动作,你得到 dispatch
引用并传递对它(dispatch
)采取行动。
所以基本上它应该看起来像这样:
const dispatch = useDispatch()
dispatch(foo())
您可以从 react-redux DOCS
中获取更多详细信息