javascript - react : How could we check if a state's parameter is not undefined?

标签 javascript reactjs

您好,感谢您抽出宝贵的时间!

我目前正在学习 React、Flux 教程:https://app.pluralsight.com/library/courses/react-flux-building-applications/table-of-contents

我面临的困难是,当我尝试创建新作者时,当我在它输出的表单上写入时:

Uncaught TypeError: Cannot read property 'firstName' of undefined
    at ManageAuthorPage._this.setAuthorState (manageAuthorPage.js:20)
    at HTMLUnknownElement.callCallback (react-dom.development.js:542)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:581)
    at Object.invokeGuardedCallback (react-dom.development.js:438)
    at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:452)
    at executeDispatch (react-dom.development.js:836)
    at executeDispatchesInOrder (react-dom.development.js:858)
    at executeDispatchesAndRelease (react-dom.development.js:956)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:967)
    at Array.forEach (<anonymous>)
    at forEachAccumulated (react-dom.development.js:935)
    at processEventQueue (react-dom.development.js:1112)
    at runEventQueueInBatch (react-dom.development.js:3607)
    at handleTopLevel (react-dom.development.js:3616)
    at handleTopLevelImpl (react-dom.development.js:3347)
    at batchedUpdates (react-dom.development.js:11082)
    at batchedUpdates (react-dom.development.js:2330)
    at dispatchEvent (react-dom.development.js:3421)
ManageAuthorPage._this.setAuthorState @ manageAuthorPage.js:20
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421

在浏览器中它详细说明:

×
TypeError: Cannot read property 'firstName' of undefined
ManageAuthorPage._this.setAuthorState
C:/Users/YonePC/WebstormProjects/flux/src/components/authors/manageAuthorPage.js:20
  17 | setAuthorState = (event) => {
  18 |     let field = event.target.name;
  19 |     let value = event.target.value;
> 20 |     if (this.state.author.firstName !== null) {
  21 |         this.state.author[field] = value;
  22 |     } else {
  23 |         this.state = {
View compiled
▶ 16 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

所以,正如你所看到的,我尝试检查 this.state.author.firstName 是否为空,以便为我们正在创建的作者创建一个新状态,如果不是,那么我们正在编辑一个现有状态,并且我们应该得到书面并更新它。

manageAuthorPage.js

import React from 'react';
import {AuthorForm} from "./authorForm";
import toastr from 'toastr';
import AuthorStore from "../../stores/authorStore";
import {AuthorActions} from "../../actions/myAuthorActions";

class ManageAuthorPage extends React.Component {
    state = {
        author: {
            id: '',
            firstName: '',
            lastName: '',
        },
    };

    setAuthorState = (event) => {
        let field = event.target.name;
        let value = event.target.value;
        if (this.state.author.firstName !== null) {
            this.state.author[field] = value;
        } else {
            this.state = {
                author: {
                    id: '',
                    firstName: '',
                    lastName: '',
                },
            };
        }
        return this.setState({author: this.state.author});
    };

    saveAuthor = (event) => {
        event.preventDefault();
        AuthorActions.createAuthor(this.state.author);
        toastr.success('Author saved ;=)');
    };

    componentDidMount = () => {
        const queryAuthorId = this.props.location.pathname; //from the path '/author:id'
        const authorId = queryAuthorId.substr(queryAuthorId.lastIndexOf("/") + 1);

        if (authorId) {
            this.setState({author: AuthorStore.getAuthorById(authorId)});
        }
        // console.log(authorId.substr(authorId.lastIndexOf("/") + 1));

    };

    render() {
        return (
            <AuthorForm author={this.state.author}
                        onChange={this.setAuthorState}
                        onSave={this.saveAuthor}/>
        );
    };
}

export {ManageAuthorPage}

我还包括了子组件,因为它们对于这个问题可能很重要:

import React from 'react';
import {Input} from "../common/textInput";
import Link from "react-router-dom/es/Link";

class AuthorForm extends React.Component {


    render() {
        const {firstName = '', lastName = '', id = ''} = this.props.author || {};

        return (
            <form>
                <h1>Manage author</h1>
                <Input
                    name="firstName"
                    label="First Name"
                    value={firstName}
                    onChange={this.props.onChange}
                />

                <Input
                    name="lastName"
                    label="Last Name"
                    value={lastName}
                    onChange={this.props.onChange}
                />

                <button type="submit" value="Save" className="btn btn-default" onClick={this.props.onSave}><Link
                    to="/authors">Save
                    author</Link>
                </button>
            </form>
        );
    }
}

export {AuthorForm}

我认为更深的 child 与这个困难无关,但为了清楚起见,我将其包括在内:

import React from 'react';
import PropTypes from 'prop-types';

class Input extends React.Component {


    render() {
        let wrapperClass = 'form-group';
        if (this.props.error && this.props.error.length > 0) {
            wrapperClass += ' ' + 'has-error';
        }
        return (
            <div className={wrapperClass}>
                <label htmlFor={this.props.name}>{this.props.label}</label>
                <div className="field">
                    <input type="text"
                           name={this.props.name}
                           className="form-control"
                           placeholder={this.props.placeholder}
                           ref={this.props.name}
                           value={this.props.value}
                           onChange={this.props.onChange}
                    />
                    <div className="input">{this.props.error}</div>
                </div>
            </div>
        );
    }
}


export {Input};

此外,我们这里还有我按照教程编写的完整应用程序:https://github.com/YoneMoreno/ReactFluxAuthorsPageTutorial

我还阅读了信息:

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/undefined

How to check for "undefined" in JavaScript?

How to determine if variable is 'undefined' or 'null'?

你能帮我吗???

感谢您的宝贵时间。

最佳答案

请注意:

null === undefined // false! 

可以说..

let a = undefined 
a === undefined // true 

但是..

a === null // false
a == null // true

所以像这样的东西可能会帮助你:

 if (this.state.author.firstName !== undefined) { 
        this.state.author[field] = value;
    } 

或者检查 null 和未定义

 if (this.state.author.firstName != null) {  
            this.state.author[field] = value;
        } 

关于javascript - react : How could we check if a state's parameter is not undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791268/

相关文章:

c# - Bing map 路线优化

javascript - 带有 ui.router 的 AngularJs 如何为其子项设置身份验证

Javascript 函数不适用于 html 中的多个按钮单击

javascript - 更新 Redux reducer 中的嵌套对象

javascript - 如何检查父元素是否包含具有 useEffect 和 UseRef 的特定类的子元素?

javascript - 预期有一个赋值或函数调用,但在 React 中看到了表达式 no-unused-expressions 错误

reactjs - React-jss : Warning: Rule is not linked. 缺少工作表选项 "link: true"

javascript - Ajax 调用阻止其他 javascript 代码

javascript - 如何使用 React Material UI 将分页添加到长列表中?

JavaScript:检测窗口开始改变位置的时刻