使用state而不是外部类变量?

时间:2017-11-22 17:55:05

标签: javascript reactjs

我想使用保存在我的状态而不是外部类变量的数据(我的意思是语言,如果你看下面的代码)

在getSuggestion中,我将languages.filter(lang....更改为this.state.myState.filter(lang...,但它不起作用

似乎无法触及this.state.myState

错误出现在getSuggestion

中的line return inputLength === 0 ? [] : this.state.myState.filter(lang =>
 import Autosuggest from 'react-autosuggest';

// Imagine you have a list of languages that you'd like to autosuggest.
const languages = [
  {
    name: 'C',
    year: 1972
  },
  {
    name: 'Elm',
    year: 2012
  },

];

// Teach Autosuggest how to calculate suggestions for any given input value.
const getSuggestions = value => {
  const inputValue = value.trim().toLowerCase();
  const inputLength = inputValue.length;

  return inputLength === 0 ? [] : languages.filter(lang =>
    lang.name.toLowerCase().slice(0, inputLength) === inputValue
  );
};

// When suggestion is clicked, Autosuggest needs to populate the input
// based on the clicked suggestion. Teach Autosuggest how to calculate the
// input value for every given suggestion.
const getSuggestionValue = suggestion => suggestion.name;

// Use your imagination to render suggestions.
const renderSuggestion = suggestion => (
  <div>
    {suggestion.name}
  </div>
);

class Example extends React.Component {
  constructor() {
    super();

    // Autosuggest is a controlled component.
    // This means that you need to provide an input value
    // and an onChange handler that updates this value (see below).
    // Suggestions also need to be provided to the Autosuggest,
    // and they are initially empty because the Autosuggest is closed.
    this.state = {
      value: '',
      suggestions: []
      myState: [
  {
    name: 'C',
    year: 1972
  },
  {
    name: 'Elm',
    year: 2012
  }
] ,

    };
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    });
  };

  // Autosuggest will call this function every time you need to update suggestions.
  // You already implemented this logic above, so just use it.
  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  // Autosuggest will call this function every time you need to clear suggestions.
  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  render() {
    const { value, suggestions } = this.state;

    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: 'Type a programming language',
      value,
      onChange: this.onChange
    };

    // Finally, render it!
    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        inputProps={inputProps}
      />
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您似乎试图在课程外的某个功能中访问this,因此this中的getSuggestions将无法定义。

如果需要在课堂外定义getSuggestions,则需要进行两项更改:

  1. getSuggestions定义为普通function而不是箭头功能,以便我们可以手动设置getSuggestions&#39} this个对象。
  2. 使用Function.prototype.call()getSuggestions的指定值来呼叫this
  3. 我写了几个例子来说明我的观点。首先,请注意下面的示例,其中getSuggestions是箭头函数,并且通过Example类的方法调用:

    &#13;
    &#13;
    const getThis = () => {
    
        console.log(this === window || this === undefined); // this is coerced to window or undefined (Strict Mode)
    };
    
    class Example {
    
        onSuggestionsFetchRequested() {
    
            console.log(this); // prints correctly 
            getThis();
        };
    }
    
    var x = new Example();
    
    x.onSuggestionsFetchRequested(); // prints true once
    &#13;
    &#13;
    &#13;

    getThis中,this对象将为Windowundefined(严格模式)。

    为了使上面的设置工作,我们进行了上面提出的两个更改:

    &#13;
    &#13;
    const getThis = function() { // change #1: use function() {} vs. () => {}
    
        console.log(this); // correct value for this
    };
    
    class Example {
    
        onSuggestionsFetchRequested() {
    
            console.log(this);
            getThis.call(this); // change #2: use call()
        };
        
        // NOTE: in your code, define onSuggestionsFetchRequested using arrow function syntax like so:
        // onSuggestionsFetchRequested = () => { ... }; 
        // I did not use the arrow syntax above so that this example would run in the browser, 
        // but you would need to in order to use onSuggestionsFetchRequested in callbacks. 
    }
    
    var x = new Example();
    
    x.onSuggestionsFetchRequested();
    &#13;
    &#13;
    &#13;

    注意:我在上面进行了一些小修改,以便在浏览器中运行代码段。也就是说,我在您的代码中将onSuggestionsFetchRequest定义为类方法而不是类属性(使用箭头函数语法)。对于您的用例,您希望使用箭头函数语法定义onSuggestionsFetchRequest,以便可以在回调中使用它。