[英]react-redux re-rendering on componentDidMount
I'm using React with Redux with multiple reducers.我正在将 React 与 Redux 与多个减速器一起使用。
I have a component in which I want to fetch data from multiple reducers but each time I make a call to action it re-renders the component (obviously...)我有一个组件,我想在其中从多个减速器获取数据,但是每次我调用操作时,它都会重新渲染该组件(显然......)
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
);
}
my question is what the best practice for such issue ?我的问题是此类问题的最佳做法是什么?
or any other options...或任何其他选择...
The component rerenders every time there is state change... You can and you should... Here is an example from an old project:每次有状态更改时,组件都会重新渲染......你可以而且你应该......这是一个旧项目的例子:
First action creator:第一个动作创建者:
export const fetchPosts = () => async (dispatch) => {
const response = await axios.get('/posts');
dispatch({ type: 'FETCH_POSTS', payload: response.data });
};
Second action creator:第二个动作创建者:
export const fetchUser = id => async dispatch => {
const response = await axios.get(`/users/${id}`);
dispatch({ type: 'FETCH_USER', payload: response.data });
};
And both combined: ( note, it's making use of lodash but you do not have to... )两者结合起来:(注意,它使用了 lodash 但你不必...... )
export const fetchPostsAnUsers = () => async (dispatch, getState) => {
await dispatch(fetchPosts());
const userIds = uniq(map(getState().posts, 'userId'));
userIds.forEach(id => dispatch(fetchUser(id)));
};
This was a use case to cut down on the number of calls made to the api but the same holds true for your use case...这是一个减少对 api 调用次数的用例,但同样适用于您的用例......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.