简体   繁体   English

反应-onChange函数'this.state'未定义

[英]React - onChange function 'this.state' is undefined

I'm experimenting with React and I'm trying to create a Search to filter a list of items. 我正在试验React,并且试图创建一个搜索来过滤项目列表。 I have two components, the main one displaying the list of items which calls the Search component. 我有两个组件,主要的一个显示调用Search组件的项目列表。

I have an onChange function that sets the term in the state as the input value and then calls searchItems from the main component to filter the list of items. 我有一个onChange函数,该函数将状态中的term设置为输入值,然后从主要组件中调用searchItems来过滤项列表。 For some reason in searchItems , this.state is undefined. 由于searchItems某些原因, this.state是未定义的。 I thought adding bind to onInputChange in the Search component would sort it out but it did not make any difference. 我认为在Search组件中将bind添加到onInputChange可以解决该问题,但是没有任何区别。 Maybe there's something I'm missing. 也许我缺少一些东西。

Main Component 主要成分

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;

Search Component 搜索组件

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;

You didn't bind searchItems() in the Items component. 您没有在Items组件中绑定searchItems()

Try changing it to an arrow function: 尝试将其更改为箭头功能:

searchItems = () => {
  // blah
}

or otherwise binding it in the constructor() : 或以其他方式将其绑定到constructor()

constructor() {
  // blah
  this.searchItems = this.searchItems.bind(this);
}

or when you call it. 或致电时。

You can read more about this here . 你可以阅读更多关于this 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM