2017-10-24 1 views
1

Ich bekomme this.props ist nicht definiert, wenn die Warnmeldung sweetalert2 verwendet wird. Ich versuche einen Benutzer bestätigen zu lassen, bevor ich sein Profil lösche, aber ich nehme an, dass dies etwas zu tun hat.Verwenden von Sweet Alert 2 Das Erhalten von this.props ist nach der Verwendung der Warnmeldung nicht definiert.

Hier ist der Code. Alles ist korrekt an Redux angeschlossen, da ich andere Orte habe, die ich anrufe this.props und es funktioniert ganz gut, also werde ich nur die Funktion platzieren, wo dies bricht, aber wenn du denkst, dass dieser Beitrag davon profitieren würde, den ganzen Code zu haben wird eine Bearbeitung vornehmen.

Die Funktion wird mit einem onClick Ereignis von einer Schaltfläche aufgerufen. Ich habe console.log und die Taste ist voll funktionsfähig und ruft die Funktion:

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

Um die Fehlermeldung zu klären Ich werde ein Bild von der Konsole hinzufügen: enter image description here


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); 
+0

Wie/Wo nennst du 'this.deleteProfile()'? – bennygenel

+0

Hinzugefügt in Bearbeitung @ bennygenel good catch –

+0

Ich sehe nichts falsch mit Ihrem Code, da Sie dies verbindlich sind. Können Sie die vollständige Fehlermeldung hinzufügen? Sagt es "Requisiten" ist undefined oder "deleteProfile"? – bennygenel

Antwort

2

Versuchen zu binden Ihre deleteProfile-Funktion für die Klasse im Konstruktor mit

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

Oder Sie können die Definition der Funktion ändern und eine Pfeilfunktion verwenden, um sie zu definieren.

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

und entfernen Sie die bind vom onClick Handler

+0

Jeder Grund, wie ich zuvor getan hat, funktionierte nur gut, als alles, was ich tat, war console.log ('Funktion namens') in der deleteProfile-Funktion? Hat es das Versprechen hinzugefügt, das es gebrochen hat? –

+1

console.log hat nicht auf den 'this' Wert zugegriffen, also hat es funktioniert. In Ihrer Funktion 'deleteProfile' verweist' '' 'standardmäßig auf die Funktion, also gab es anfangs, als Sie versuchten, auf' this.props' zuzugreifen, kein 'requiss'-Feld in der Funktion und es gab die Fehlermeldung. Wenn Sie die Funktion mithilfe der Syntax in der Antwort an die Klasse anbinden, können Sie auf das 'this 'verweisen, das auf die Klasse verweist, und auf' this.props'. Hoffe das löscht deine Verwirrung. – palsrealm

+0

Große Erklärung! Hat dir vielmals geholfen –

Verwandte Themen