首页 > 解决方案 > (TypeError):无法读取未定义的属性“道具”

问题描述

我有一个名为 Search 的组件负责任何搜索

代码:

class Search extends Component {
  state = {
    searchResult: []
  }

  async componentDidMount() {
    await this.props.searchAssets(this.props.match.params.name);
    this.handleState();
  }

  handleState() {
    this.setState({ searchResult: this.props.searchResult });
  }

  async handleSearch(e) {
    e.preventDefault();
    await this.props.searchAssets(e.target.q.value);
    this.handleState()
  }

  render() {
    return (
      <div className="content-block">
        <form onSubmit={this.handleSearch} className="search-form">
            <button>بحـث</button>
            <input type="text" defaultValue={this.props.match.params.name} name="q" placeholder="Est: Game of thrones, Vikings or Deadpool" />
        </form>
        <div className="display-latest">
          ***the div where search results are shown***
        </div>
      </div>
    )
  }
}

它工作得非常好,直到我尝试在页面上添加另一个搜索表单,我试图让它重用来自 redux 的操作,但它一直给我这个错误

(TypeError):无法读取未定义的属性“道具”

即使我尝试使用构造函数并绑定它。

另外,如果有更好的方法可以在不加载页面的情况下触发搜索,我很乐意做笔记。:)

标签: javascriptreactjsredux

解决方案


该函数handleStatehandleSearch缺少对 this 的引用。您可以通过以下两种方式获得参考:

  1. 如果您使用transform-class-properties的似乎是您的情况,您可以将函数更改为箭头函数。
  2. 您必须使用以下方式在构造函数中绑定函数:

    this.handleState = this.handleState.bind(this);

这些中的任何一个都应该解决这里的问题。


推荐阅读