【问题标题】:React Autosuggest throwing error on clicking the suggestionsReact Autosuggest 在点击建议时抛出错误
【发布时间】:2020-06-28 06:33:34
【问题描述】:

我在我的代码中使用 React-autosuggest,但我面临的问题是,每当我点击任何建议时,我都会收到错误提示

未捕获的类型错误:无法读取未定义的属性“修剪”

这是我的代码

var subjectsToBeSearched= []

const getSuggestions = value => {
  const inputValue = value.trim().toLowerCase();
  const inputLength = inputValue.length;

  return inputLength === 0
    ? []
    :subjectsToBeSearched.filter(
        lang => lang.name.toLowerCase().slice(0, inputLength) === inputValue
      );
};
const getSuggestionValue = suggestion => suggestion.name;
`
const renderSuggestion = suggestion => <div>{suggestion.name}</div>;

export default class Searchbar extends Component {
  state = {
    language_id: "",
    subjects: [],
    value: "",
    suggestions: []
  };
  onChange = event => {
    this.setState({
      value: event.target.value
    },()=>console.log(this.state.value));
  };
  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    });
  };
  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  componentWillMount() {
    let languageid = localStorage.getItem("language_id");
    var userdata = window.localStorage.getItem("userdata");

    if (languageid == null) {
      localStorage.setItem("language_id", 0);
    }
    this.setState({ language_id: languageid, userdata: JSON.parse(userdata) });
    this.getAllSubjects();
  }

  getAllSubjects = async () => {
    let details = {
      language_id: this.state.language_id
    };

    this.setState({
      response: fetch("http://18.221.47.207:3000/get_subjects", {
        method: "GET",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "Cache-Control": "max-age=31536000"
        }
      })
        .then(response => response.json())
        .then(responseJson => {
          this.setState(
            {
              subjects: responseJson
            },
            () => {
              let subjectsToBeFind = this.state.subjects.map(item => {
                return { id: item.subject_id, name: item.subject_name };
              });
              subjectsToBeSearched=subjectsToBeFind
            }
          );
        })
        .catch(error => {
          this.setState({
            loading: false
          });
          swal("Warning!", "Check your network!", "warning");
          console.log(error);
        })
    });
  };

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

    return (
      <div className={`${styles.InputHeaderSearchDiv} `}>
        <Autosuggest 
           inputProps={inputProps}
          className={`${styles.InputHeaderSearch}`}
          suggestions={suggestions}
          onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
          onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        //   alwaysRenderSuggestions={true} 
          getSuggestionValue={getSuggestionValue}
          renderSuggestion={renderSuggestion}
        />
        <div className={`${styles.SearchIcon}`}>
          <img src={SearchIcon} alt="search" />
        </div>
      </div>
    );
  }
}

所以当我点击任何建议时,我只需要安慰并做一些事情,但它马上就会抛出错误

【问题讨论】:

  • 如错误信息所说,onSuggestionsFetchRequested 中的Autosuggest回调在某些使用操作下可能会返回undefined

标签: javascript reactjs autosuggest


【解决方案1】:

当您单击建议时,inputProps 中“value”键的值未定义,这就是您收到无法修剪错误的原因。

我所做的解决方法是添加一个名为“onSuggestionSelected”(Documentation for onSuggestionSelected found here)的道具,并添加一个函数,将 inputProps 中的“value”键的值设置为您希望输入标签在单击后应具有的任何值事件。

THIS IS HOW MY AUTOSUGGEST LOOKSLIKE

HERE IS MY FUNCTION

【讨论】:

    【解决方案2】:

    在我的例子中,只需将 inputProps 的值设置为字符串就可以了

    <Autosuggest
    inputProps: {
    value: whateverValue.toString()
    

    【讨论】:

    • 这帮助我找出了问题,因为它将输入文本设置为[object Object]。显然,我将 inputProps 值设置为对象而不是预期的字符串属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2021-12-22
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多