gpt4 book ai didi

javascript - 试图模拟 API 响应延迟 : Cannot read property 'then' of undefined

转载 作者:行者123 更新时间:2023-11-30 14:53:40 24 4
gpt4 key购买 nike

在我的 React 应用程序中,我试图伪造模拟 API 响应的延迟

Uncaught TypeError: Cannot read property 'then' of undefined

createDraft() {
// Post to Mock API
const newDraft = {
name: this.state.draftName,
created_by: this.props.user,
created: getDate()
};

/* ERROR HERE */
this.props.create(newDraft).then((res) => {
console.log(' res', res);
// Display loading spinner while waiting on Promise

// Close modal and redirect to Draft Summary view
this.props.closeModal();
});
}

Action :

export const create = newDraft => dispatch => all()
.then(() => setTimeout(() => {
dispatch({
type: CREATE,
newDraft
});
return 'Draft created!';
}, 2000))
.catch(() => {
dispatch({
type: REQUEST_ERROR,
payload: apiErrors.BAD_REQUEST
});
});

连通区域:

const mapDispatchToProps = dispatch => ({
create: (newDraft) => { dispatch(create(newDraft)); }
});

export const CreateDraftModalJest = CreateDraftModal;

export default connect(cleanMapStateToProps([
'user'
]), mapDispatchToProps)(CreateDraftModal);

也试过同样的结果

function DelayPromise(t) {
return new Promise(((resolve) => {
setTimeout(resolve, t);
}));
}

export const create = newDraft => dispatch => all()
.then(DelayPromise(2000))
.then(() => {
console.log('created called', newDraft);
dispatch({
type: CREATE,
newDraft
});
})
.then(() => 'Draft created!')
.catch(() => {
dispatch({
type: REQUEST_ERROR,
payload: apiErrors.BAD_REQUEST
});
});

最佳答案

有可能您的 this.props.create() 操作创建者未绑定(bind)调度,因此未按预期返回 promise 。

你是否正确使用了 react-redux connect()?

编辑:

您的 mapDispatchToProps 没有返回 promise 。改为这样做:

const mapDispatchToProps = dispatch => ({
create: (newDraft) => dispatch(create(newDraft)),
});

关于javascript - 试图模拟 API 响应延迟 : Cannot read property 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47720692/

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