React - onChange函数'this.state'未定义

j.g*_*ima 2 javascript reactjs

我正在尝试使用React,我正在尝试创建一个搜索来过滤项目列表.我有两个组件,主要显示调用搜索组件的项目列表.

我有一个onChange函数,它将term状态设置为输入值,然后searchItems从主组件调用以过滤项目列表.出于某种原因searchItems,this.state未定义.我想加入bindonInputChange在搜索组件将整理出来,但它并没有任何区别.也许有一些我想念的东西.

主要部分

import React, { Component } from 'react';
import _ from 'lodash';

import Search from './search';

class Items extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            items: []
        };
    }

    componentDidMount() {
        fetch("[url].json")
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        isLoaded: true,
                        items: result
                    });
                }
            ),
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                })
            }
    }

    searchItems(term) {
        const { items } = this.state;
        const filtered = _.filter(items, function(item) {
            return item.Name.indexOf(term) > -1;
        });

        this.setState({ items: filtered });
    }

    render() {
        const { error, isLoaded, items } = this.state;

        if (error) {
            return <div>Error: {error.message}</div>;
        }
        else if (!isLoaded) {
            return <div>Loading...</div>;
        }
        else {
            return (
                <div>
                    <Search onSearch={this.searchItems}/>
                    <ul>
                        {items.map(item => (
                            <li key={item.GameId}>
                                {item.Name}
                            </li>
                        ))}
                    </ul>
                </div>
            )
        }
    }
}

export default Items;
Run Code Online (Sandbox Code Playgroud)

搜索组件

import React, { Component } from 'react';

class Search extends Component {
    constructor(props) {
        super(props);

        this.state = {
            term: ''
        };
    }

    render() {
        return (
            <div>
                <input type="text" placeholder="Search" value={this.state.term} onChange={event => this.onInputChange(event.target.value)} />
            </div>
        );
    }

    onInputChange(term) {
        this.setState({ term });
        this.props.onSearch(term);
    }
}

export default Search;
Run Code Online (Sandbox Code Playgroud)

Col*_*rdo 13

你没有绑定searchItems()Items组件.

尝试将其更改为箭头功能:

searchItems = () => {
  // blah
}
Run Code Online (Sandbox Code Playgroud)

或以其他方式约束它constructor():

constructor() {
  // blah
  this.searchItems = this.searchItems.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

或者当你打电话给它.

你可以this 在这里阅读更多信息.