React组件方法this.state.myState从child返回后未定义

React component method this.state.myState undefined after returning from child

本文关键字:child 返回 未定义 myState 组件 方法 this state React      更新时间:2023-09-26

我在React中有一个父组件(BookApplication)和一个子组件(SearchBox)。SearchBox有一个输入字段,并且应该将输入返回给父类来处理事件。这是工作良好,但当我回到父组件在方法handleSearchthis.state...是未定义的。

TypeError: Cannot read property 'books' of undefined

但是searchInput有它应有的价值。但是我还需要从这个。state.books网站买书我知道,在方法handleSearch我在它的范围内工作,所以this....是handleSearch的上下文…但我如何得到它的组件的参数BookApplication吗?我还在学习javascript,我认为这应该不是一个问题,因为一个函数总是可以使用它的父对象的变量?

class BookApplication extends React.Component {
    constructor() {
        super();
        this.state = {books: []};
    }
    componentDidMount() {
        $.get(PATH, function (result) {
            this.setState({
                books: result
            });
        }.bind(this));
    }
    handleSearch(searchInput) {
        //Sort the books list
        var sortedList = [];
        this.state.books.map(
            function (currentBook) {
                currentBook.keys().forEach(
                    function (key, pos) {
                        if (key.contains(searchInput)) {
                            sortedList.push(currentBook)
                        }
                    }
                )
            }
        );
    }
render() {
        return (
            <div>
                <SearchBox onSearch={this.handleSearch}/>
                <div className="book-list">
                    {this.state.books.map(function (currentBook) {
                        return <Book book={currentBook} key={currentBook.id}/>;
                    }) }
                </div>
            </div>
        );
    }

这里也是我的搜索框:

class SearchBox extends React.Component {
constructor(props) {
    super(props);
    this.state = {searchFieldInput: ''};
    this.handleSearchChange = this.handleSearchChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}
handleSearchChange(event) {
    this.setState({searchFieldInput: event.target.value});
}
handleSubmit(e) {
    //Prevent the browser's defeault action of submitting the form
    e.preventDefault();
    var searchFieldInput = this.state.searchFieldInput.trim();
    //Call the passed callback function
    this.props.onSearch({searchFieldInput: searchFieldInput});
}
render() {
    return (
        <div className="book-search">
            <input
                type="text"
                value={this.state.searchFieldInput}
                onChange={this.handleSearchChange}
                placeholder="Search..."
                className="search-bar"
            />
            <button onClick={this.handleSubmit} className="search-button">Search</button>
        </div>
    );
}

}

如果您的问题是如何从子组件获取父组件的上下文,那么尝试

class ParentComponent extends React.Component {
    ...
    ...
    clickHandler(event){}
    render(){
        <ChildComponent parent={this}/>
    }
}
class ChildComponent extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        let parent = this.props.parent;
        return <button onClick={parent.clickHandler}></button>
    }
}

这里会出现错误

componentDidMount() {
    $.get(PATH, function (result) {
        this.setState({
            books: result
        });
    }.bind(this));
}

因为回调函数中的this没有引用到组件的上下文。你应该把组件的上下文放在变量

componentDidMount() {
    let self = this;
    $.get(PATH, function (result) {
        self.setState({
            books: result
        });
    }.bind(this));
}

最后决定是

constructor(props) {
    super(props);
    this.state = {books: []};
    //add the following line into your code
    this.handleSearch = this.handleSearch.bind(this);
}