【问题标题】:ReactJS Parent component state is getting overridden by Child component stateReactJS父组件状态被子组件状态覆盖
【发布时间】:2018-10-05 10:36:22
【问题描述】:

我上周开始学习 reactjs。我正在创建一个反应应用程序,该应用程序按书名和作者管理书名。我在书籍页面上设计了这样的反应组件,

Books 组件是 NewBook 和 BookList 组件的父组件。我在 Books 和 NewBook 中使用 state。一个用于书籍数组,另一个用于添加新书。我想通过调用作为道具传递给孩子的父母的addBook(函数)来更新NewBook(孩子)中的书(父母)的状态。但是我遇到了一个问题,即其 addBook 函数中的父状态被覆盖。

Books.js

import React from "react";

import { BookList } from "./BookList";
import { NewBook } from "./NewBook";


export class Books extends React.Component {
    constructor() {
        super();
        this.state = {
            books: [
                {title: "The Black Swan", author: "Nassim Nicholas Taleb"},
                {title: "The Lean Startup", author: "Eric Ries"}
            ]
        };
    }

    addBook(title, author) {
        console.log("adding..");
        const newBooks = this.state.books;
        newBooks.push({title: title, author: author});
        this.setState({
            books: newBooks
        });
    }

    render() {
        return (
            <div className="col-md-6 offset-3"> 
                <NewBook onAdd={this.addBook} defaultTitle={''} defaultAuthor={''} />

                <BookList books={this.state.books}/>
            </div>
        );
    }
}

NewBook.js

import React from "react";

export class NewBook extends React.Component {
    constructor(props) {
        super();
        this.state = {
            title: props.defaultTitle,
            author: props.defaultAuthor
        };
    }

    add() {
        this.props.onAdd(this.state.title, this.state.author);
        this.setState({title: this.props.defaultTitle, author: this.props.defaultAuthor});
    }

    updateTitle(event) {
        this.setState({title: event.target.value});
    }

    updateAuthor(event) {
        this.setState({author: event.target.value});
    }

    render() {
        return (
            <div>
                <div className="form-group">
                    <textarea 
                        className="form-control col-md-12" 
                        rows="2" placeholder="I am reading this book named" 
                        value={this.state.title}
                        onChange={(event) => this.updateTitle(event)} />
                </div>
                <div className="form-group">
                    <label htmlFor="author" className="font-italic font-weight-light">by</label>
                    <input className="form-control form-control-sm col-md-12" 
                        id="author" placeholder="this author" 
                        value={this.state.author}
                        onChange={(event) => this.updateAuthor(event)}/> 
                </div>
                <div className="form-group">
                    <button disabled={this.state.title === '' || this.state.author === ''} onClick={() => this.add()} className="btn btn-primary btn-lg btn-block">Add</button>
                </div>
            </div>
        );
    } }

BookList.js(这个组件没有问题)

import React from "react";
import { Link } from "react-router-dom";

export class BookList extends React.Component {
    render() {
        var books = this.props.books;
        return (
            <ul>
                {books.map((item, i) => <li key={i}><Link to={{ pathname: "/quotes", search: "?title=" + item.title }}>{item.title}</Link> by <Link to={{ pathname: "/quotes", search: "?author=" + item.author }}>{item.author}</Link></li>)}
            </ul>
        );
    }
}

点击添加时出现错误

adding..
Uncaught TypeError: Cannot read property 'books' of undefined
    at Object.addBook [as onAdd] (Books.js:44)
    at NewBook.add (NewBook.js:40)
    at onClick (NewBook.js:93)
    at HTMLUnknownElement.callCallback (react-dom.development.js:104)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:142)
    at Object.invokeGuardedCallback (react-dom.development.js:191)
    at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:205)
    at executeDispatch (react-dom.development.js:470)
    at executeDispatchesInOrder (react-dom.development.js:492)
    at executeDispatchesAndRelease (react-dom.development.js:590)

这个新手错过了什么吗?顺便说一句,我正在使用

"react": "^16.3.1",
"react-dom": "^16.3.1",

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您需要将addBook 绑定到构造函数中的类,否则addBook 中的this 将引用函数本身而不是类:

    this.addBook = this.addBook.bind(this);
    

    或者,将其更改为不将this 绑定到函数的箭头函数。

    addBook = (title, author) => {
      ...
    }
    

    【讨论】:

    【解决方案2】:

    你需要在构造函数中绑定你的事件处理方法,否则'this'不会引用任何东西。

    https://reactjs.org/docs/handling-events.html

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2015-04-15
      • 1970-01-01
      • 2019-11-29
      • 2015-12-02
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      • 2018-04-20
      相关资源
      最近更新 更多