簡體   English   中英

在組件級別上React / Redux鏈接異步thunk操作

[英]React/Redux chaining async thunk actions at component level

在組件級別上鏈接依賴的異步redux thunk操作的推薦方法是什么?

我的用例是一個流程,我需要首先進行api調用以檢索用戶對象,然后獲取該用戶的所有博客文章。 問題在於,第二次獲取所有博客帖子的調用取決於第一次調用的返回值(用戶ID)。

我的組件:

export default class UserDetail extends React.Component
{
  componentDidMount() {
    this.props.getUser()
  }
}

this.props.getUser()返回一個我映射到props的用戶對象:

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

我需要在this.props.getUser()完成之后調用this.props.getBlogPostsForUser(USER_ID) 建議以這種方式鏈接動作的最佳實踐是什么?

你可以打鏈子

const getUser = username => dispatch => request(username)
  .then(res => dispatch({ type: GET_USER })
  .catch(err => dispatch({ type: GET_USER_ERR }));

const getBlogPostsForUser = userId => dispatch => request(userId)
  .then(res => dispatch({ type: GET_BLOGS }))
  .catch(err => dispatch({ type: GET_BLOGS_ERR }));


const getUserAndPosts = username => (dispatch, getState) => dispatch(getUser(username))
  .then(() => {
    const user = getState().user;
    return dispatch(getBlogPostsForUser(user.id));
  });

或者,您可以將它們合並為一個調度,然后將它們捆綁在一起

const getUserAndPosts = (username) => dispatch => request(username)
  .then((userData) => {
    dispatch(setUser(userData));
    return request(user.id)
      .then(blogs => dispatch(setBlog(blogs)));
  });

您必須標識componentDidUpdate生命周期方法中出現的新用戶響應,才能調用另一個從屬調用。 像這樣

export default class UserDetail extends React.Component {
  componentDidMount() {
    this.props.getUser();
  }
  componentDidUpdate(prevProps) {
    const { user, getBlogPostsForUser } = this.props;
    const { user: prevUser } = prevProps;
    if (prevUser !== user) {
      const { USER_ID } = user; // derive USER_ID from user object. I dont know path. you can accordingly change
      getBlogPostsForUser(USER_ID);
    }
  }
}

這應該工作。 歡迎反饋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM