【发布时间】:2019-04-17 12:00:46
【问题描述】:
我目前正在使用这种模式,但感觉有点不对劲。我不认为 redux thunk 应该返回一个字符串,并且组件应该只访问通过连接的 props 获取的数据。我可能错了,但有没有更好、更惯用的方法呢?
我想将两个 thunk 分开,以便我可以单独调用每个。
// actions
const putCustomer = ...;
const putBooking = ...;
// thunks
export async function fetchCustomer(customerId) {
return dispatch => {
const customer = await customerApi.fetch(customerId);
dispatch(actions.putCustomer( {customer} ));
};
}
export async function fetchBooking(bookingId) {
return dispatch => {
const booking = await bookingApi.fetch(bookingId);
dispatch(actions.putBooking( {booking} ));
// I AM RETURNING THE BOOKING DATA HERE
return booking;
};
}
// component
class MyComponent extends React.Component {
async componentWillMount() {
const booking = await this.props.dispatch(fetchBooking(this.props.bookingId));
// I WANT TO ACCESS THE BOOKING DATA HERE
this.props.dispatch(fetchCustomer(booking.customerId));
}
}
问题已更新
- 添加了一些我想访问数据的 cmets
【问题讨论】:
-
所以你能详细说明一下吗,如果我理解正确,那么你的意思是如果你调度动作,那么在那之后获取数据的正确方法是什么?
-
我的意思是我应该从 thunk 中返回数据(我标记为“我在此处返回预订”的行),所以是的,我认为您理解正确。我知道我可以连接组件并通过连接的道具获取数据,但我想立即在 componentWIllMount 函数的下一行中获取预订数据,我将更新问题。
标签: reactjs redux redux-thunk