簡體   English   中英

未捕獲的類型錯誤:無法將未定義或 null 轉換為 object React JS

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

我正在嘗試讓我的照片博客/phlog 管理器組件正常工作。 但是控制台說通過道具有一個未定義的 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)
        });
    }

錯誤發生在 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;

當道具來自父組件 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();

在這里,我將 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'>

這是 object、phlogToEdit 作為道具傳遞給提到的子組件的地方

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

@Jaycee444 解決了它是父組件的問題!

phlogToEdit={this.state.phlogToEdit}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM