【问题标题】:react-redux re-rendering on componentDidMountreact-redux 在 componentDidMount 上重新渲染
【发布时间】:2019-06-18 23:39:28
【问题描述】:

我将 React 与带有多个 reducer 的 Redux 一起使用。
我有一个组件,我想从多个 reducer 中获取数据,但每次我发出号召性用语时,它都会重新呈现组件(显然......)

async componentDidMount() {
  await this.props.getBooksNamesAsync();
  await this.props.getAuthorsNamesAsync();
  await this.props.getSubscribersAsync();

  this.props.setFilter(
    this.props.book.bookNames,
    this.props.author.authorNames,
    this.props.subscriber.subscriberNames
  );
}
  • this.props.getBooksNamesAsync() 是对图书的操作。
  • this.props.getAuthorsNamesAsync() 是对作者的操作。
  • this.props.getSubscribersAsync() 是对订阅者的操作。

我的问题是此类问题的最佳做法是什么?

  • 每次操作都重新渲染组件是否合法?
  • 我是否应该在一个地方编写另一个包含所有这些操作的操作? 这是安静的代码重复,我更愿意避免它......

或任何其他选项...

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    每次状态变化时组件都会重新渲染...您可以而且应该...这是一个旧项目的示例:

    第一个动作创建者:

    export const fetchPosts = () => async (dispatch) => {
      const response = await axios.get('/posts');
    
      dispatch({ type: 'FETCH_POSTS', payload: response.data });
    };
    

    第二个动作创建者:

    export const fetchUser = id => async dispatch => {
      const response = await axios.get(`/users/${id}`);
    
      dispatch({ type: 'FETCH_USER', payload: response.data });
    };
    

    两者结合:(注意,它正在使用 lodash 但你不必...

    export const fetchPostsAnUsers = () => async (dispatch, getState) => {
      await dispatch(fetchPosts());
      const userIds = uniq(map(getState().posts, 'userId'));
      userIds.forEach(id => dispatch(fetchUser(id)));
    };
    

    这是一个减少对 api 的调用次数的用例,但同样适用于您的用例......

    【讨论】:

    • 所以这是将 2 个动作 fetchPosts() 和 fetchUser(id) 组合到一个新动作 fetchPostsAndUsers() 中的情况。除此之外,我还需要调用另一个动作 setFilter() 我应该将它也组合到那个动作中吗?一个动作是不是太有逻辑了?
    • @kaycee... 是的,这正是它的本质...这就是为什么我使用lodash 链接并“稍微清理一下代码...还有其他解决方案好吧...但是如果您在一个团队中工作,我发现这是最“可以理解的”...
    猜你喜欢
    • 2018-12-12
    • 2020-11-27
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多