javascript - 为什么我收到 TypeError : _this. props ."functionName"is not a function ReactJS

标签 javascript reactjs firebase google-cloud-firestore

所以我有以下脚本,自从我编辑它们以来已经有一段时间了,但据我记得上次我检查时它们工作得完美无缺。但现在,由于某种原因,editProfile 函数已停止工作。我认为这是一个具有约束力的问题,但我似乎无法找出答案。我尝试将该函数添加到脚本本身,而不是从 authActions 导入它,但这仍然不起作用。简而言之,问题出在以下代码中(以下摘录来自下面发布的第二个脚本)

handleSubmit = (e) => {
            e.preventDefault();
            this.props.editProfile(this.state);
            this.props.onClose()

        }

编辑个人资料和 onClose 都不起作用。下面列出了错误。两个函数都会抛出相同的错误。换句话说,如果我删除 'this.props.editProfile(this.state);'对于“this.props.onClose()”,我会收到相同的错误

import {storage} from 'config/fbConfig';
import {toastr} from 'react-redux-toastr'

export const signIn = (credentials) => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signInWithEmailAndPassword(
      credentials.email,
      credentials.password
    ).then(() => {
      dispatch({ type: 'LOGIN_SUCCESS' });
      toastr.success('ברוכים הבאים לאתר שותפים')
      }).catch((err) => {
      dispatch({ type: 'LOGIN_ERROR', err });
      toastr.error('אירעה שגיאת אימות.')
    });


  }
}

export const signInwithPhoneNumber = () => {
  return (dispatch, getState, {
    getFirebase
  }) => {
   // const firebase = getFirebase();


  }
}



export const signOut = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signOut().then(() => {
      dispatch({ type: 'SIGNOUT_SUCCESS' })
    });
  }
}

export const signUp = (newUser) => {
  return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firebase = getFirebase();
    const firestore = getFirestore();

    firebase.auth().createUserWithEmailAndPassword(
      newUser.email, 
      newUser.password
    ).then(resp => {
      return firestore.collection('Partners').doc(resp.user.uid).set({
        displayName: newUser.displayName,
        phoneNumber: newUser.phoneNumber,
        email: newUser.email,
        location: null,
        displayImage: "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg",

      });
    }).then(() => {
      dispatch({ type: 'SIGNUP_SUCCESS' });
      //dispatch(send_EmailVerification())
    }).catch((err) => {
      dispatch({ type: 'SIGNUP_ERROR', err});
    });
  }
}

export const editProfile = (profile) => {
  return (dispatch, getState, {
    getFirebase, getFirestore
  }) => {
    const firestore = getFirestore();
      const Puid = getState().firebase.auth.uid;
      if (profile.uploadedImages !== ''){
       const uploadedImages = profile.uploadedImages
            const uploadTask = storage.ref(`images/${uploadedImages.name}`).put(uploadedImages);
            uploadTask.on('state_changed',
                (snapshot) => {
                    // progrss function ....
                    const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
                    console.log(progress);
                },
                (error) => {
                    // error function ....
                    console.log(error);
                },
                () => {
                    // complete function ....
                    storage.ref('images').child(uploadedImages.name).getDownloadURL().then(url => {
                      // displayImage = url;

                      firestore.collection('Partners').doc(Puid).set({
                        displayName: profile.displayName,
                        phoneNumber: profile.phoneNumber,
                        location: profile.location,
                        displayImage: url

                      }).then(() => {
                        toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                        dispatch({
                          type: 'EDIT_PROFILE_SUCCESS'
                        })

                      }).catch(function (error) {
                        // An error happened.
                        dispatch({
                          type: 'EDIT_PROFILE_ERROR'
                        })
                        toastr.error('אופס! אירעה תקלה :|')
                      });
                    })
                });
              }
              else{

                 firestore.collection('Accounts').doc(Puid).set({
                   ...profile,
                   displayName: profile.displayName,
                   phoneNumber: profile.phoneNumber,
                   location: profile.location,
                   displayImage: profile.displayImage

                 }).then(() => {
                   dispatch({
                     type: 'EDIT_PROFILE_SUCCESS'
                   })
                   toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                 }).catch(function (error) {
                   // An error happened.
                   dispatch({
                     type: 'EDIT_PROFILE_ERROR'
                   })
                   toastr.error('אופס! לא יכולנו לעדכן את הפרופיל')
                 });
              }



  }
}

export const send_EmailVerification = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().currentUser.sendEmailVerification().then(() => {
      //email send
      dispatch({ type: 'EMAIL_VERIFICATION_SUCCESS' })
      toastr.info('הודעה', 'הודעת אימות נשלחה למייל')
    }).catch(function (error) {
      // An error happened.
      toastr.error('The message')
    });;
  }
}

这是需要使用上面脚本中的“editProfile”函数的 buildProfile 脚本。

import React, { Component } from 'react'
import 'assets/css/Css.css'
import {editProfile} from 'store/actions/authActions'




import { Button,Icon} from 'react-materialize';

import GridContainer from "components/Grid/GridContainer.jsx";
import GridItem from "components/Grid/GridItem.jsx";
import Card from "components/Card/Card.jsx";
import withStyles from "@material-ui/core/styles/withStyles";



import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import { Hidden } from '@material-ui/core';

import $ from 'jquery';
import 'react-redux-toastr/lib/css/react-redux-toastr.min.css'
import Properties from 'components/Profile/properties'

import { clearSelectedProperty } from "../../store/actions/propertyActions";

// @material-ui/icons

class BuildProfile extends Component {
    state = {
        displayName: (this.props.profile !== null) ? this.props.profile.displayName : '',
        location: (this.props.profile !== null) ? this.props.profile.location : '',
        displayImage: (this.props.profile !== null) ? this.props.profile.displayImage : '',
        phoneNumber: (this.props.profile !== null) ? this.props.profile.phoneNumber : '',
        uploadedImages: '',
        file:''
     }

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    handleImagesUpload = (e) => {
        if (e.target.files) {
            const uploadedImages = e.target.files[0]
            const file =  URL.createObjectURL(e.target.files[0])
            this.setState(() => ({
                uploadedImages,
                file
            }));
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.editProfile(this.state);
        this.props.onClose()

    }
    handleSelectChange = (e) => {
        this.setState({
            location: e.target.value
        })
    }

    render() {

        const {profile, onClose} = this.props;
        const {
            displayName,
            location, displayImage, phoneNumber
        } = this.state
        const locationOptions = [
            {label: "תל אביב", value: 'תל אביב', type: "location"},
            {label: " ירושליים ", value: 'ירושליים', type: "location"},
            {label: "חיפה", value: 'חיפה', type: "location"}
        ];
        //if (auth.uid) return <Redirect to='/' />

        return (

            <GridContainer  justify="center">
                <GridItem xs={13} sm={12} md={4}>
                <Card >

<form onSubmit={this.handleSubmit}>
                        <div className="modal-header"><h3 style={{marginRight:-17}} className='center-align'>יצרירת פרופיל</h3></div>
                        <div className="modal-content" style={{padding:"6rem",marginTop:-40}}>
                        <div className="col s5 m4 l3 center">

                                    <img className="profile-pic circle" height="150" style={{maxWidth:200,marginTop:-25}}
                                         src={this.state.uploadedImages? this.state.file :  "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg"}
                                         alt="profile pic"

                                         />

                                         {console.log(this.state.file)}
                                         <div className="row">

                                                                                     <input type="file" id="uploadedImages" onChange={this.handleImagesUpload}  style={{marginRight:38,maxWidth:150,overflowX:"auto"}}/>
                                                                                     </div>
                                </div>
                            <div className="row">


                                    <div className="input-field" style={{width:300}}>
                                        <input id="displayName" type="text" className="validate"

                                        placeholder={null}

                                               value={this.props.displayName}
                                               onChange={this.handleChange}/>
                                        <label className="active" htmlFor="displayName">שם מלא</label>
                                    </div>


                            </div>
                            <div className="row" style={{marginTop:-10}}>
                                    <div className="input-field" style={{width:300}}>
                                        <input id="phoneNumber" type="text" className="validate"
                                               value={profile.phoneNumber}
                                               onChange={this.handleChange}/>
                                        <label className="active" htmlFor="phoneNumber">מס׳ טלפון</label>
                                    </div>
                                </div>

                                <div className="col s12 m6 input-field">

                                    <select id="location" style={{display:"block", marginRight:-10}}
                                            onChange={this.handleSelectChange}
                                            value={null}
                                            required>
                                        <option value="" disabled defaultValue>Location
                                        </option>
                                        {locationOptions.map(function (option) {
                                            return <option key={option.value}
                                                           value={option.value}>{option.label}</option>
                                        })}
                                    </select>
                                    <label style={{marginTop:-37,marginRight:-10, fontSize:"12px"}}>איזור</label>

                                </div>
                                <div className="col s12 m6 input-field" style={{marginTop:30,marginRight:60}}>
                        <Button type="submit" waves="light" style={{backgroundColor:"#ff6969"}}>
המשך
</Button>

             </div>

         </div>




                    </form>
                    </Card>

                    </GridItem>
                            </GridContainer>

        )
    }
}

const mapStateToProps = (state, props) => {
    console.log(state,props)
     return {
       authError: state.auth.authError,
       auth: state.firebase.auth,
       properties: state.firestore.ordered.Properties,
       partner: state.firestore.ordered.Partners,
       profile: state.firebase.profile,
       selectedProperty: state.property,
       invitation: state.firestore.ordered.Invitations

     }

   }

   const mapDispatchToProps = (dispatch) => {
     return {

     }
   }

   export default compose(

     connect(mapStateToProps, mapDispatchToProps),
     firestoreConnect((props) => {
         if (!props.auth.uid) {
           props.history.push('/signin')
           return []
         }
         let propid = null
            if(props.invitation !== undefined){
                propid = props.invitation[0].propid
            }
            return [
             {
               collection: 'Invitations',
              doc: props.match.params.inviteid

             },
             {
               collection: 'Partners',
               doc: props.auth.uid
             },
             {
                 collection: 'Properties',
                 doc: propid
             },

           ]
        }

    )
    )(BuildProfile)   

我不断收到以下错误

enter image description here

最佳答案

BuildProfile 组件在 props 中没有 prop editProfile 或者它不是函数。 我看到您正在导入 editProfile 函数:

import {editProfile} from 'store/actions/authActions'

您可能想像这样调用editProfile:

handleSubmit = (e) => {
            e.preventDefault();
            editProfile(this.state);
            onClose();
}

关于javascript - 为什么我收到 TypeError : _this. props ."functionName"is not a function ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60281113/

相关文章:

javascript - 按照 my-app 教程中的说明进行操作时,React JS 抛出错误

java - Firebase实时数据库获取push()引用

javascript - react : CSS breaks using classList in IE and Edge

swift - 从 Firebase 检索数组

android - 如何根据 Kotlin 中的键值从 firebase 读取数据

javascript - 如何在 angularJs 中通过单击按钮添加 div

javascript - Jquery 追加 img 和 a

Javascript:5 个中的随机数,在全部使用之前不重复

javascript - 通过 ajax JSON 获取未定义

javascript - 由于 `@withGesture`,项目未编译