首页 > 解决方案 > 无法读取 React 状态下未定义的属性“名称”

问题描述

我正在尝试制作一个将图像上传到firebase存储的组件。但是在 onsubmit 函数中会发生以下错误。可以加载 render() 中的 {this.state.uploadfile.name}。

TypeError:无法读取未定义的属性“名称”

我该如何解决?

如果您知道比我凌乱的代码更好的方法,请告诉我。

class CreateProject extends Component {
    state = {
        title:'',
        content:'',
        uploadfile:'',
        setImageUrl:'',
    }

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

    handleSubmit = (e) =>{
        e.preventDefault();
        this.props.createProject(this.state)
        this.props.history.push('/')
    }

    onDrop = acceptedFiles => {
      if (acceptedFiles.length > 0) {
        this.setState({ uploadfile: acceptedFiles[0] })
      }
    }
  
    handleSubmitImg = (e) =>{
      e.preventDefault()
      //this.props.sampleteFunction()
    };

    parseFile = (file) =>{
      const updatedFile = new Blob([file], { type: file.type });
      updatedFile.name = file.name;
      return updatedFile;
    }

    onSubmit = (event) => {
      event.preventDefault();
      var updatedFile = this.state.updatedFile;
      if (updatedFile === "") {
        console.log("File is not chosen");
      }
      console.log("aaaaaaaaaaaa"+updatedFile)
      const uploadTask = storage.ref(`/images/${this.state.updatedFile.name}`).put(updatedFile);
      uploadTask.on(
        firebase.storage.TaskEvent.STATE_CHANGED,
        this.next,
        this.error,
        this.complete
      );
    };
    next = snapshot => {
      const percent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log(percent + "% done");
      console.log(snapshot);
    };
    error = error => {
      console.log(error);
    };
    complete = () => {
      var updatedFile = this.state.updatedFile
      // get image-URL after Uoloding
      storage
        .ref("images")
        .child(updatedFile.name)
        .getDownloadURL()
        .then(fireBaseUrl => {
          this.setState({ setImageUrl: fireBaseUrl })
        });
    };

  render() {
   const maxSize = 3 * 1024 * 1024;
   const dropzoneStyle = {
  }

    const {auth} = this.props

    console.log("UP"+this.uploadfile  );
    if(!auth.uid) return <Redirect to="/signin" />
    return (
      <Dropzone
      onDrop={this.onDrop}
      accept="image/png,image/jpeg,image/gif,image/jpg"
      inputContent={(files, extra) => (extra.reject ? 'Image files only' : 'Drag Files')}
      styles={dropzoneStyle}
      minSize={1}
      maxSize={maxSize}
    >
      {({ getRootProps, getInputProps }) => (

      <div className="container">
        <form onSubmit={this.handleSubmit} className="white">
            <h5 className="grey-text text-darken-3">
                Create Project
            </h5>
            <div className="input-field">
                <label htmlFor="title">Title</label>
                <input type="text" id="title" onChange={this.handleChange}/>
            </div>

            <div className="input-field">
                <label htmlFor="content">Project Content</label>
                <textarea id="content" className="materialize-textarea" onChange={this.handleChange}></textarea>
            </div>
            <div className="input-field">
                <button className="btn pink lighten-1 z-depth-0">Create</button>
            </div>
               </form>
            <div {...getRootProps()}>
                <input {...getInputProps()} />
                
                <p>Drop</p>
                {this.state.uploadfile ? <p>Selected file: {this.state.uploadfile.name}</p> : null}
                
                {this.state.uploadfile ? (<Thumb key={0} file={this.state.uploadfile } />) :null}
            </div>
            <form onSubmit={this.onSubmit}>
           <button>Upload</button>
          </form>
 
      </div>
  )}
</Dropzone>

    
    )
  }
}

标签: reactjsreact-dropzone

解决方案


您正在使用 并且uploadfile:'',您正在state尝试访问updatedFileonSubmit

调整

var updatedFile = this.state.updatedFile;

var updatedFile = this.state.uploadfile;


推荐阅读