简体   繁体   English

未捕获的类型错误:无法将未定义或 null 转换为 object React JS

[英]Uncaught TypeError: Cannot convert undefined or null to object React JS

I am trying to get my photo blog/phlog manager component functional.我正在尝试让我的照片博客/phlog 管理器组件正常工作。 However the console says the there an undefined object through props.但是控制台说通过道具有一个未定义的 object 。

import React, { Component } from 'react';
import axios from 'axios';
import DropzoneComponent from 'react-dropzone-component';

import "../../../node_modules/react-dropzone-component/styles/filepicker.css";
import "../../../node_modules/dropzone/dist/min/dropzone.min.css";

class PhlogEditor extends Component {
    constructor(props) {
        super(props);

        this.state = {
            id: '',
            phlog_status: '',
            phlog_image: '',
            editMode: false,
            position: '',
            apiUrl: 'http://127.0.0.1:8000/phlogapi/phlog/',
            apiAction: 'post'
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.componentConfig = this.componentConfig.bind(this);
        this.djsConfig = this.djsConfig.bind(this);
        this.handlePhlogImageDrop = this.handlePhlogImageDrop.bind(this);
        this.deleteImage = this.deleteImage.bind(this);

        this.phlogImageRef = React.createRef();
    }

    deleteImage(event) {
        event.preventDefault();
        axios
            .delete(
                `http://127.0.0.1:8000/phlogapi/phlog/${this.props.id}/delete`,
                { withCredentials: true }
            )
            .then(response => {
                this.props.handlePhlogImageDelete();
            })
            .catch(error => {
                console.log('deleteImage failed', error)
        });
    }

The error is occuring at Object.keys(this.props.phlogToEdit).length>0错误发生在 Object.keys(this.props.phlogToEdit).length>0

    componentDidUpdate() {
        if (Object.keys(this.props.phlogToEdit).length > 0) {
            // debugger;
            const {
                id,
                phlog_image,
                phlog_status,
                position
            } = this.props.phlogToEdit;

            this.props.clearPhlogsToEdit();

            this.setState({
                id: id,
                phlog_image: phlog_image || '',
                phlog_status: phlog_status || '',
                position: position || '',
                editMode: true,
                apiUrl: `http://127.0.0.1:8000/phlogapi/phlog/${this.props.id}/update`,
                apiAction: 'patch'
            });
        } 
    }

    handlePhlogImageDrop() {
        return {
            addedfile: file => this.setState({ phlog_image_url: file })
        };
    }


    componentConfig() {
        return {
          iconFiletypes: [".jpg", ".png"],
          showFiletypeIcon: true,
          postUrl: "https://httpbin.org/post"
        };
    }

    djsConfig() {
        return {
          addRemoveLinks: true,
          maxFiles: 3
        };
    }

    buildForm() {
        let formData = new FormData();

        formData.append('phlog[phlog_status]', this.state.phlog_status);

        if (this.state.phlog_image) {
            formData.append(
                'phlog[phlog_image]',
                this.state.phlog_image
            );
        }

        return formData;
    }

    handleChange(event) {
        this.setState({
          [event.target.name]: event.target.value
        });
    }

    handleSubmit(event) {
        axios({
            method: this.state.apiAction,
            url: this.state.apiUrl,
            data: this.buildForm(),
            withCredentials: true
        })
        .then(response => {
            if (this.state.phlog_image) {
                this.phlogImageRef.current.dropzone.removeAllFiles();
            }

            this.setState({
                phlog_status: '',
                phlog_image: ''
            });

            if (this.props.editMode) {
                this.props.handleFormSubmission(response.data);
            } else {
                this.props.handleSuccessfulFormSubmission(response.data);
            }
        })
        .catch(error => {
            console.log('handleSubmit for phlog error', error);
        });

     event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} className='phlog-editor-wrapper'>
                <div className='one-column'>
                    <div className='image-uploaders'>
                        {this.props.editMode && this.props.phlog_image_url ? (
                            <div className='phlog-manager'>
                                <img src={this.props.phlog.phlog_image_url} />

                            <div className='remove-image-link'>
                                <a onClick={() => this.deleteImage('phlog_image')}>
                                    Remove Photos
                                </a>
                            </div>
                        </div>
                    ) : (
                       <DropzoneComponent
                            ref={this.phlogImageRef}
                            config={this.componentConfig()}
                            djsConfig={this.djsConfig()}
                            eventHandlers={this.handlePhlogImageDrop()}
                        >
                            <div className='phlog-msg'>Phlog Photo</div>
                        </DropzoneComponent>
                    )}
                </div>
                    <button className='btn' type='submit'>Save</button>
                </div>
            </form>
        );
    }
}

export default PhlogEditor;

I do not understand how the object is empty when the props are coming from the parent component phlog-manager.js:当道具来自父组件 phlog-manager.js 时,我不明白 object 如何为空:

    import React, { Component } from "react";
import axios from "axios";

import PhlogEditor from '../phlog/phlog-editor';

export default class PhlogManager extends Component {
    constructor() {
        super();

Here I define phlogToEdit as an object to pass as props to phlogEditor child component在这里,我将 phlogToEdit 定义为 object 作为道具传递给 phlogEditor 子组件

        this.state = {
            phlogItems: [],
            phlogToEdit: {}
        };

        this.handleNewPhlogSubmission = this.handleNewPhlogSubmission.bind(this);
        this.handleEditPhlogSubmission = this.handleEditPhlogSubmission.bind(this);
        this.handlePhlogSubmissionError = this.handlePhlogSubmissionError.bind(this);
        this.handleDeleteClick = this.handleDeleteClick.bind(this);
        this.handleEditClick = this.handleEditClick.bind(this);
        this.clearPhlogToEdit = this.clearPhlogToEdit.bind(this);
    }

    clearPhlogToEdit() {
        this.setState({
            phlogToEdit: {}
        });
    }

    handleEditClick(phlogItem) {
        this.setState({
            phlogToEdit: phlogItem
        });
    }

    handleDeleteClick(id) {
        axios
            .delete(
                `http://127.0.0.1:8000/phlogapi/phlog/${id}`,
                { withCredentials: true }
            )
            .then(response => {
                this.setState({
                    phlogItems: this.state.phlogItems.filter(item => {
                        return item.id !== id;
                    })
                });

                return response.data;
            })
            .catch(error => {
                console.log('handleDeleteClick error', error);
        });
    }

    handleEditPhlogSubmission() {
        this.getPhlogItems();
    }

    handleNewPhlogSubmission(phlogItem) {
        this.setState({
            phlogItems: [phlogItem].concat(this.state.phlogItems)
        });
    }

    handlePhlogSubmissionError(error) {
        console.log('handlePhlogSubmissionError', error);
    }

    getPhlogItems() {
        axios
          .get('http://127.0.0.1:8000/phlogapi/phlog',
            {
               withCredentials: true 
            }
          )
          .then(response => {
              this.setState({
                  phlogItems: [...response.data]
              });
          })
          .catch(error => {
              console.log('getPhlogItems error', error);
          });
    }

    componentDidMount() {
        this.getPhlogItems();
    }

    render() {
        return (
            <div className='phlog-manager'>
                <div className='centered-column'>

This is where the object, phlogToEdit is being passed as props to child component mentioned这是 object、phlogToEdit 作为道具传递给提到的子组件的地方

                    <PhlogEditor
                        handleNewPhlogSubmission={this.handleNewPhlogSubmission}
                        handleEditPhlogSubmission={this.handleEditPhlogSubmission}
                        handlePhlogSubmissionError={this.handleEditPhlogSubmission}
                        clearPhlogToEdit={this.clearPhlogToEdit}
                        phlogToEdit={this.phlogToEdit}
                    />
                </div>
            </div>
        );
    }
}

@Jaycee444 solved the problem it was the parent component! @Jaycee444 解决了它是父组件的问题!

phlogToEdit={this.state.phlogToEdit} phlogToEdit={this.state.phlogToEdit}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的类型错误:无法将未定义或 null 转换为 object 反应 - Uncaught TypeError: Cannot convert undefined or null to object React 未捕获的TypeError:无法将未定义或null转换为对象 - Uncaught TypeError: Cannot convert undefined or null to object JS setter 返回 ''undefined'' 并且 getter 导致 Uncaught TypeError TypeError: Cannot convert undefined or null to object - JS setters return ''undefined'' and the getter causes Uncaught TypeError TypeError: Cannot convert undefined or null to object React JS:TypeError:无法将未定义或空值转换为对象 - React JS: TypeError: Cannot convert undefined or null to object TypeError:无法在反应中将未定义或 null 转换为 object - TypeError: Cannot convert undefined or null to object in react React: Uncaught TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous> )</anonymous> - React: Uncaught TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) Vue.JS:未捕获(承诺)类型错误:无法将未定义或 null 转换为 object - Vue.JS: Uncaught (in promise) TypeError: Cannot convert undefined or null to object d3.v5.min.js:2 未捕获类型错误:无法将未定义或 null 转换为 object - d3.v5.min.js:2 Uncaught TypeError: Cannot convert undefined or null to object 如何解决Uncaught TypeError:无法将undefined或null转换为对象 - how to solve Uncaught TypeError: Cannot convert undefined or null to object 如何解决这个“Uncaught TypeError:无法将undefined或null转换为object” - How to resolve this “ Uncaught TypeError: Cannot convert undefined or null to object ”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM