ReactJS父组件状态被子组件状态

时间:2018-04-25 04:18:10

标签: reactjs

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

enter image description here

Books组件是NewBook和BookList组件的父组件。我在Books和NewBook中使用state。一个用于一系列书籍,另一个用于添加新书。我想通过调用从父作为prop传递给子项的父项的addBook(函数)来更新NewBook(child)中Books(parent)的状态。但我遇到的问题是,其中的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",

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:1)

您需要在构造函数中绑定事件处理方法,否则&#39;这个&#39;不会提及任何事情。

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