【问题标题】:What is the correct way to access data fetched from a redux thunk function?访问从 redux thunk 函数获取的数据的正确方法是什么?
【发布时间】: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


【解决方案1】:

在理想情况下,如果您调度某些操作,流程将如何进行:

建议 UI 可以绑定 state 并通过 reducer 修改 state,它是单向流。您尝试返回的数据可以通过状态进行管理,并且调度程序可以修改该状态

【讨论】:

  • 所以我想我的评论下面的行'//我想在此处访问预订数据'应该在 componentWIllReceiveProps 中,当道具更新时?好像有点乱
  • 不,当 dispatch 被调用时,它会改变应用的状态,从 mapStateToProps 你可以得到改变的状态
  • 但在我上面的例子中,我只想调用一次fetchCustomer(booking.customerId)。这应该去哪里?
  • 在行动中,它将执行您获取客户任务并将结果保存在状态中,因此如果您需要该结果,您可以从状态中获取
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2019-03-15
  • 2019-10-20
  • 2021-08-22
  • 1970-01-01
相关资源
最近更新 更多