【问题标题】:(TypeError): Cannot read property 'props' of undefined(TypeError):无法读取未定义的属性“道具”
【发布时间】:2019-05-09 08:37:32
【问题描述】:

我有一个名为 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): 无法读取未定义的属性“props”

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

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

【问题讨论】:

  • 问题在于this.handleSearch,将其与handlesearch 绑定或将handlesearch 定义为箭头函数。
  • @MayankShukla 我尝试了箭头功能,它确实工作得很好,谢谢!介意添加它作为答案吗? :)

标签: javascript reactjs redux


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2021-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多