gpt4 book ai didi

javascript - 在 React 组件中链接 redux Action 创建者 Promise.then()

转载 作者:行者123 更新时间:2023-12-03 13:55:35 25 4
gpt4 key购买 nike

我计划在我的 redux 操作创建器中使用 axios 进行异步调用和 promise 。目前还没有可以使用的 API,所以我将内容保存在本地。

如何使以下内容可从 react 组件内部链接?

Action 创建者

export function fetchResultsIfNeeded() {
return (dispatch, getState) => {
if (true) {
return dispatch(fetchResults(day, hash));
}

else {return Promise.resolve();}
};
}

export function fetchResults(day, hash) {
return (dispatch) => {
// Dispatch something here

return new Promise(resolve => setTimeout(resolve, 1000)).then(() => {
// Do some stuff here
// Dispatch some other stuff here as well
}); // Want to chain on this promise in react component
};
}

react 组件

import { fetchResultsIfNeeded } from 'actions';

// Class based react component
checkResults(periodFrom, periodTo) {
this.props.fetchResultsIfNeeded([periodFrom, periodTo]).then(() => {/* Do some stuff here */});
}

// Connected via react redux
export default connect(null, { fetchResultsIfNeeded })(component);

当前收到以下错误,是否仍在等待react-redux等?

Uncaught TypeError: Cannot read property 'then' of undefined

将 Action 创建器和组件放入笔中(不知道如何显示完整代码)

Full component code , Full action creator code

最佳答案

我假设您正在使用redux-thunk。您需要从 Action 创建器内的解析函数返回。正确的流程应该是:

export function fetchResults(day, hash) {
return (dispatch) => {

dispatch(...).then(
( ) => {
// Do some stuff here
return dispatch(...)
}
)
}
}

关于javascript - 在 React 组件中链接 redux Action 创建者 Promise.then(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41511250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com