2

this.props使用 sweetalert2 警告警报时,我得到的是未定义的。我试图让用户在删除他们的个人资料之前确认,但我认为这一定是对 this.props 做些什么?

这是代码。一切都正确连接到 redux,因为我有其他地方我正在调用this.props它并且它工作得很好,所以我只会将函数放置在它被破坏的地方,但是如果你觉得这篇文章会从拥有所有代码中受益,我会进行编辑。

该函数是使用onClick来自按钮的事件调用的。我有console.log并且按钮完全正常工作并调用该函数:

 <button
  className="btn btn-danger btn-lg btn-block"
  onClick={this.deleteProfile.bind(this)}
 >
  DELETE Profile
 </button>

为了澄清错误消息,我将添加控制台图片: 在此处输入图像描述


import React, { Component } from 'react';
import { connect } from 'react-redux';
import swal from 'sweetalert2/dist/sweetalert2.all.min.js';

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'
      }
    };
  }

  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',
        type: 'error'
      });

      return;
    }

    this.props
      .updateProfile(currentUser, params)
      .then(response => {
        swal({
          title: `${response.username} Updated!`,
          text: 'Thank you for updating your profile',
          type: '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',
        type: 'error'
      });

      return;
    }

    swal({
      title: 'Are you sure?',
      text: 'Your Profile will be lost forever!',
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then(() => {
      this.props
        .deleteProfile(profile)
        .then(() => {
          this.props.history.push('/');
          swal('Deleted!', 'Your Profile has been deleted.', '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>
            <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">
                  User since: {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 ? null : (
              <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.bind(this)}
                    >
                      DELETE Profile
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  }
}

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

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

export default connect(stateToProps, dispatchToProps)(Profile);
4

1 回答 1

2

尝试使用将您的函数绑定deleteProfile到构造函数中的类

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

或者您可以更改函数的定义并使用箭头函数来定义它。

deleteProfile=()=>{
  ... //rest of function body
 }

并从onClick处理程序中删除绑定

于 2017-10-24T14:20:09.313 回答