[英]redux async with redux thunk doesn't work with @connect
我嘗試使用setTimeout作為rest api的模擬,但我的redux似乎有缺陷。
https://codesandbox.io/s/1zr78rp48j
部分代碼
@connect(state => state.items, { approveItem })
export default class Items extends Component {
render() {
return (
<div>
<div>status: {this.props.item.status}</div>
<button onClick={() => approveItem()}>{this.props.loading ? 'loading...' : 'Approve'}</button>
</div>
);
}
}
我想知道為什么這個簡單的流程不起作用,我的減速器中的setTimeout函數是否有意義? 我正在使用redux-thunk。
我已經糾正了你的代碼,看一看
問題出在你的班上
export class Items extends Component {
render() {
console.log(approveItem);
return (
<div>
<div>status: {this.props.items && this.props.items.item.status}</div>
<button onClick={() => this.props.approveItem()}>Approve </button>
</div>
);
}
}
// start of code change
const mapStateToProps = (state) => {
return { items: state.items };
};
const mapDispatchToProps = (dispatch) => {
return {
approveItem: () => dispatch(approveItem())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Items);
如果你想讓redux采取動作創建者並將它們包裝在一個將調度結果的函數中,你必須將動作創建者的對象傳遞給mapDispatchToProps(你正確地這樣做)。
但是在組件中您沒有使用包裝的動作創建器,您正在使用導入的approveItem
創建自動分派的動作創建者的正確代碼是:
import React, { Component } from "react";
import { connect } from "react-redux";
import { approveItem } from "./actions";
//mapDispatchToProps is an object here, all function members of the object
// will be treated as action creators and wrapped in a function that when
// called will automatically dispatch their result
const mapDispatchToProps = { approveItem };
@connect(state => state.items, mapDispatchToProps)
export default class Items extends Component {
render() {
//use the wrapped action creator found on this.props
console.log(this.props.approveItem);
return (
<div>
<div>status: {this.props.item.status}</div>
<button onClick={() => this.props.approveItem()}>Approve </button>
</div>
);
}
}
您可以手動將動作創建者包裝在將調度其結果(動作)的函數中。 通過將函數傳遞給mapDispatchToProps。
當您想要隔離組件而不是將所有減少器和操作轉儲到一堆時,通常就是這種情況。 應用程序將操作包裝在{type:"ITEM",action:actualItemComponentAction}
。 由於組件不知道如何將其操作包裝在由應用程序處理的操作中,因此應用程序需要將包裝器傳遞給返回thunk函數的操作創建器,並使用可由應用程序reducer處理的類型包裝實際操作對象。
不確定bindActionCreators如何適應這一點因為如果您手動想要將動作創建器綁定到組件,您通常不希望自動綁定它們,而是希望將組件操作包裝在應用程序操作中。
可以在此處找到正在進行的示例工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.