Javascript 在React/Redux中获取多个项目会导致无限循环并且屏幕上没有jsx?

Javascript 在React/Redux中获取多个项目会导致无限循环并且屏幕上没有jsx?,javascript,reactjs,redux,jsx,Javascript,Reactjs,Redux,Jsx,目标: 我希望能够从一个数组中获取多个配置文件,并在屏幕上列出它们。比如: John, Sandy, Drew 我正在使用react并尝试从friendRequest数组中列出用户。这个数组中充满了用户id,我想映射它们以获取用户并在屏幕上显示他/她 发生的事情是,在控制台.log(pendingFriend)中,这是一个无限循环,在本例中,两个配置文件一次又一次地被记录下来。屏幕上也没有显示jsx 这是代码 在render>return>中查看,可以看到正在映射的currentUser.fr

目标:

我希望能够从一个数组中获取多个配置文件,并在屏幕上列出它们。比如:

John, Sandy, Drew
我正在使用react并尝试从
friendRequest
数组中列出用户。这个数组中充满了用户id,我想映射它们以获取用户并在屏幕上显示他/她

发生的事情是,在
控制台.log(pendingFriend)
中,这是一个无限循环,在本例中,两个配置文件一次又一次地被记录下来。屏幕上也没有显示jsx

这是代码

在render>return>中查看,可以看到正在映射的
currentUser.friendRequests

import React, { Component } from 'react';
import { connect } from 'react-redux';
import swal from 'sweetalert';

import actions from '../../actions';
import { UpdateProfile } from '../view';
import { DateUtils } from '../../utils';

class Profile extends Component {
  constructor() {
    super();
    this.state = {
      profile: {
        image:
          'https://lh3.googleusercontent.com/EJf2u6azJe-TA6YeMWpDtMHAG6u3i1S1DhbiUXViaF5Pyg_CPEOCOEquKbX3U-drH29oYe98xKJiWqYP1ZxPGUQ545k',
        bannerImage:
          'https://lh3.googleusercontent.com/RAdfZt76XmM5p_rXwVsfQ3J8ca9aQUgONQaXSE1cC0bR0xETrKAoX8OEOzID-ro_3vFfgO8ZMQIqmjTiaCvuK4GtzI8',
        firstName: 'First Name',
        lastName: 'Last Name',
        email: 'Contact Email',
        bio: 'Bio will go here'
      }
    };

    this.deleteProfile = this.deleteProfile.bind(this);
  }

  componentDidMount() {
    const { id } = this.props.match.params;

    if (this.props.profiles[id] != null) {
      return;
    }

    this.props
      .getProfile(id)
      .then(() => {})
      .catch(err => {
        console.log(err);
      });
  }

  createUpdatedProfile(params) {
    const { id } = this.props.match.params;
    const profile = this.props.profiles[id];
    const { currentUser } = this.props.user;

    if (currentUser.id !== profile.id) {
      swal({
        title: 'Oops...',
        text: 'You do not own this profile',
        icon: 'error'
      });

      return;
    }

    this.props
      .updateProfile(currentUser, params)
      .then(response => {
        swal({
          title: `${response.username} Updated!`,
          text: 'Thank you for updating your profile',
          icon: 'success'
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  deleteProfile() {
    const { id } = this.props.match.params;
    const profile = this.props.profiles[id];
    const { currentUser } = this.props.user;

    if (currentUser.id !== profile.id) {
      swal({
        title: 'Oops...',
        text: 'You do not own this profile',
        icon: 'error'
      });

      return;
    }

    swal({
      closeOnClickOutside: false,
      closeOnEsc: false,
      title: 'Are you sure?',
      text:
        'All data related to profile will be deleted as well with the profile! If you wish to delete your profile you must type DELETE',
      icon: 'warning',
      dangerMode: true,
      buttons: true,
      content: 'input'
    }).then(value => {
      if (value === 'DELETE') {
        const userPosts = this.props.post.all.filter(p => p.profile.id === profile.id);
        const userReplies = this.props.reply.all.filter(r => r.user.id === profile.id);
        userPosts.map(post => {
          this.props.deleteRecord(post);
        });
        userReplies.map(reply => {
          this.props.deleteReply(reply);
        });
        this.props
          .deleteProfile(profile)
          .then(data => {
            return this.props.logoutUser();
          })
          .then(data => {
            this.props.history.push('/');
            swal('Deleted!', 'Your Profile has been deleted.', 'success');
            return null;
          })
          .catch(err => {
            console.log(err);
          });
      }
      swal({
        title: 'Profile not deleted',
        text: 'Make sure you type "DELETE" with caps',
        icon: 'error'
      });
    });
  }

  addFriend() {
    const { id } = this.props.match.params;
    const profile = this.props.profiles[id];
    const { currentUser } = this.props.user;
    if (currentUser == null || profile == null) {
      swal({
        title: 'Oops...',
        text: 'Must be logged in, and user must exist',
        icon: 'error'
      });
      return;
    }
    const friendRequests = profile.friendRequests || [];
    const params = {};
    friendRequests.push(currentUser.id);
    params.friendRequests = friendRequests;
    this.props
      .updateProfile(profile, params)
      .then(() => {
        swal({
          title: 'Success',
          text: 'Friend Request Sent',
          icon: 'success'
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    const { id } = this.props.match.params;
    const profile = this.props.profiles[id];
    const { currentUser } = this.props.user;
    const defaultProfile = this.state.profile;
    const bannerUrl =
      profile == null
        ? defaultProfile.bannerImage
        : profile.bannerImage || defaultProfile.bannerImage;
    const bannerStyle = {
      backgroundImage: `url(${bannerUrl})`,
      backgroundSize: '100%',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center'
    };
    const nameStyle = {
      background: 'rgba(255, 255, 255, 0.7)',
      borderRadius: '8px'
    };
    const imageStyle = {
      maxHeight: '150px',
      margin: '20px auto'
    };

    return (
      <div>
        {profile == null ? (
          <div>
            <h1>Profile no longer exists</h1>
          </div>
        ) : (
          <div>
            {currentUser == null ? null : currentUser.id !== profile.id ? null : (
              <div className="list-group">
                {currentUser.friendRequests
                  ? currentUser.friendRequests.map(request => {
                      this.props
                        .getProfile(request)
                        .then(pendingFriend => {
                          console.log(pendingFriend);
                          return (
                            <div key={pendingFriend.id} className="list-group-item">
                              <p>{pendingFriend.username}</p>
                            </div>
                          );
                        })
                        .catch(err => {
                          console.log(err);
                        });
                    })
                  : null}
              </div>
            )}
            <div className="jumbotron jumbotron-fluid" style={bannerStyle}>
              <div className="container" style={nameStyle}>
                <img
                  src={profile.image || defaultProfile.image}
                  style={imageStyle}
                  className="rounded img-fluid mx-auto d-block"
                />
              </div>
            </div>
            <div className="row">
              <div className="col-sm-12">
                <h1 className="display-3 text-center">{profile.username}</h1>
                <p className="lead text-center">
                  {profile.firstName || defaultProfile.firstName}{' '}
                  {profile.lastName || defaultProfile.lastName}
                </p>
                <p className="lead text-center text-muted">
                  {profile.email || defaultProfile.email}
                </p>
                <p className="text-center text-muted">
                  Became a User: {DateUtils.relativeTime(profile.timestamp)}
                </p>
                <hr className="my-4" />
                <p className="lead" style={{ border: '1px solid #e6e6e6', padding: '20px' }}>
                  {profile.bio || defaultProfile.bio}
                </p>
              </div>
            </div>
            {currentUser == null ? null : currentUser.id !== profile.id ? (
              <div className="row justify-content-center" style={{ marginBottom: '100px' }}>
                <div className="col-sm-6">
                  {profile.friendRequests ? (
                    profile.friendRequests.indexOf(currentUser.id) === -1 ? (
                      <button
                        className="btn btn-primary btn-lg btn-block"
                        onClick={this.addFriend.bind(this)}
                      >
                        Add Friend
                      </button>
                    ) : (
                      <button className="btn btn-success btn-lg btn-block">
                        Pending Friend Request
                      </button>
                    )
                  ) : (
                    <button
                      className="btn btn-primary btn-lg btn-block"
                      onClick={this.addFriend.bind(this)}
                    >
                      Add Friend
                    </button>
                  )}
                </div>
              </div>
            ) : (
              <div>
                <UpdateProfile
                  currentProfile={profile}
                  onCreate={this.createUpdatedProfile.bind(this)}
                />
                <div className="row justify-content-center" style={{ marginBottom: '100px' }}>
                  <div className="col-sm-6">
                    <button
                      className="btn btn-danger btn-lg btn-block"
                      onClick={this.deleteProfile}
                    >
                      DELETE Profile
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  }
}

const stateToProps = state => {
  return {
    profiles: state.profile,
    user: state.user,
    post: state.post,
    reply: state.reply
  };
};

const dispatchToProps = dispatch => {
  return {
    getProfile: id => dispatch(actions.getProfile(id)),
    updateProfile: (entity, params) => dispatch(actions.updateProfile(entity, params)),
    deleteProfile: entity => dispatch(actions.deleteProfile(entity)),
    deleteRecord: entity => dispatch(actions.deleteRecord(entity)),
    deleteReply: entity => dispatch(actions.deleteReply(entity)),
    logoutUser: () => dispatch(actions.logoutUser())
  };
};

const loadData = store => {
  return store.dispatch(actions.getProfile(this.props.match.params.id));
};

export default {
  loadData: loadData,
  component: connect(stateToProps, dispatchToProps)(Profile)
};
import React,{Component}来自'React';
从'react redux'导入{connect};
从“sweetalert”进口污水;
从“../../actions”导入操作;
从“../view”导入{UpdateProfile};
从“../../utils”导入{DateUtils};
类概要文件扩展了组件{
构造函数(){
超级();
此.state={
简介:{
图片:
'https://lh3.googleusercontent.com/EJf2u6azJe-TA6YeMWpDtMHAG6u3i1S1DhbiUXViaF5Pyg_CPEOCOEquKbX3U-drH29oYe98xKJiWqYP1ZxPGUQ545k',
横幅图像:
'https://lh3.googleusercontent.com/RAdfZt76XmM5p_rXwVsfQ3J8ca9aQUgONQaXSE1cC0bR0xETrKAoX8OEOzID-ro_3vFfgO8ZMQIqmjTiaCvuK4GtzI8',
名字:“名字”,
姓氏:“姓氏”,
电子邮件:“联系电子邮件”,
bio:“bio将在这里发布”
}
};
this.deleteProfile=this.deleteProfile.bind(this);
}
componentDidMount(){
const{id}=this.props.match.params;
if(this.props.profiles[id]!=null){
返回;
}
这是道具
.getProfile(id)
.然后(()=>{})
.catch(错误=>{
控制台日志(err);
});
}
createUpdatedProfile(参数){
const{id}=this.props.match.params;
const profile=this.props.profiles[id];
const{currentUser}=this.props.user;
if(currentUser.id!==profile.id){
游泳({
标题:“哎呀……”,
文本:“您不拥有此配置文件”,
图标:“错误”
});
返回;
}
这是道具
.updateProfile(当前用户,参数)
。然后(响应=>{
游泳({
标题:`${response.username}已更新!`,
文字:“感谢您更新您的个人资料”,
图标:“成功”
});
})
.catch(错误=>{
控制台日志(err);
});
}
deleteProfile(){
const{id}=this.props.match.params;
const profile=this.props.profiles[id];
const{currentUser}=this.props.user;
if(currentUser.id!==profile.id){
游泳({
标题:“哎呀……”,
文本:“您不拥有此配置文件”,
图标:“错误”
});
返回;
}
游泳({
closeOnClickOutside:false,
closeOnEsc:错,
标题:“你确定吗?”,
正文:
'与配置文件相关的所有数据也将随配置文件一起删除!如果要删除配置文件,必须键入delete',
图标:“警告”,
丹格莫德:没错,
按钮:是的,
内容:“输入”
}).然后(值=>{
如果(值=='DELETE'){
const userPosts=this.props.post.all.filter(p=>p.profile.id===profile.id);
constUserReplies=this.props.reply.all.filter(r=>r.user.id===profile.id);
userPosts.map(post=>{
此.props.deleteRecord(post);
});
userreplays.map(reply=>{
this.props.deleteReply(reply);
});
这是道具
.deleteProfile(配置文件)
。然后(数据=>{
返回此.props.logoutUser();
})
。然后(数据=>{
this.props.history.push('/');
swal('Deleted!','您的个人资料已被删除','success');
返回null;
})
.catch(错误=>{
控制台日志(err);
});
}
游泳({
标题:“未删除配置文件”,
text:'确保键入带大写字母的“DELETE”,
图标:“错误”
});
});
}
addFriend(){
const{id}=this.props.match.params;
const profile=this.props.profiles[id];
const{currentUser}=this.props.user;
if(currentUser==null | | profile==null){
游泳({
标题:“哎呀……”,
文本:“必须登录,且用户必须存在”,
图标:“错误”
});
返回;
}
const friendRequests=profile.friendRequests | |[];
常量参数={};
friendRequests.push(currentUser.id);
params.friendRequests=friendRequests;
这是道具
.updateProfile(配置文件、参数)
.然后(()=>{
游泳({
标题:"成功",,
文本:“已发送好友请求”,
图标:“成功”
});
})
.catch(错误=>{
控制台日志(err);
});
}
render(){
const{id}=this.props.match.params;
const profile=this.props.profiles[id];
const{currentUser}=this.props.user;
const defaultProfile=this.state.profile;
康斯特班纳鲁尔=
profile==null
?defaultProfile.bannerImage
:profile.bannerImage | | defaultProfile.bannerImage;
常量横幅样式={
背景图片:`url(${bannerUrl})`,
背景尺寸:“100%”,
背景重复:“不重复”,
背景位置:“中心”
};
常量名称样式={
背景:“rgba(255,255,255,0.7)”,
边界半径:“8px”
};
常量imageStyle={
最大高度:“150px”,
保证金:“20px自动”
};
返回(
{profile==null(
配置文件不再存在
) : (
{currentUser==null?null:currentUser.id!==profile.id?null:(
{currentUser.friendRequests
?currentUser.friendRequests.map(请求=>{
这是公共关系
this.props.getProfile(request)
    .then(pendingFriend => {   
     console.log(pendingFriend);
 constructor(props) {
   super(props);