reactjs - 组件多次重新渲染并重复添加默认用户
问题描述
在这一点上,我不能再直接考虑这个问题了:
我有一个可以让人们创建“基地”的应用程序。当访问一个新创建的基础组件时,该组件会获取一个用户列表,然后在新组件上呈现该列表:
componentDidMount() {
this.props.dispatch(fetchUsersOfList());
}
后台的 reducer 将用户添加到状态(如果有)。默认为:
const initialState = {
userBases: [],
}
访问新创建的组件时,我想添加(POST 请求)一个默认用户(即基础的创建者)并显示它。我只希望这样做一次,并希望通过检查防止添加不止一次:
render() {
if (
this.props.userBases.length !== 0 &&
this.props.currentBase.id !== undefined
) {
const userName = this.props.currentAuthUser;
const baseId = this.props.currentBase.id;
const acceptedMembership = true;
const isCreator = true;
this.props.dispatch(
addUserToList(baseId, userName, acceptedMembership, isCreator)
);
}
不知何故,我对 if 语句感到非常困惑,因此像这样的请求会触发数十次,如果不是数百次的话。组装一个 if 语句返回 userBases 的简单 .map(如果存在),或者添加并显示一个与 base 本身的创建者同名的默认用户有多难?
解决方案
由于您在 componentDidMount 中调用 fetchUsersOfList() 它将强制重新渲染。尝试将您的逻辑移至 componentWillMount
编辑:每次在减速器中设置状态时,它也会强制重新渲染