为什么在onclick函数中使用TypeError? -ReactJS

时间:2018-08-03 03:10:24

标签: javascript reactjs

我正在开发一个应用程序,以从API提取帖子并加载帖子。除import React from 'react' import { connect } from 'react-redux' import { compose } from 'recompose' export class Reader extends React.Component { render() { const { match, pageLevel } = this.props; console.log(match); // undefined return ( <div> <div className='reader-body'> <Book bookId={match.params.bookId} pageLevel={pageLevel} bank={bank}/> </div> ); } } Const mapStateToProps = (state) => { return { metadata: state.book.metadata, pageLevel: state.book.pageLevel } }; const authCondition = (authUser) => !!authUser; export default compose( withAuthorization(authCondition), connect(mapStateToProps, mapDispatchToProps), )(Reader); 函数外,其他一切都正常。呈现此错误后,出现 gotopost

但是不知道为什么会这样。尽管我绑定了该函数并在render()函数上方声明了该函数

下面是代码

TypeError: Cannot read property 'gotopost' of undefined

3 个答案:

答案 0 :(得分:1)

使用箭头功能:

  this.props.posts.map((post) => {

答案 1 :(得分:0)

这是JS的常见错误。当您使用内部函数时,此范围内的var this不再在类之外。解决方法是将this分配给方法顶部的另一个变量。

render(){
  const self = this;

    return (<div className="row mt-5">
      {
        this.props.posts.map(function(post){
            return <div className="col-md-6 mb-2" key={post.id}>
                <div className="card" >
 // use self instead this
                    <a href={post.link} onClick={self.gotopost.bind(this)} className="btn btn-primary">Go somewhere</a>
                </div>
              </div>
          })
      }
      </div>
    )
  }

答案 2 :(得分:0)

在给this的函数中,

map不会是您期望的。您可以将函数bind设为this,也可以使用箭头函数来使用周围的词法范围,而this就是您想要的。

class Allposts extends React.Component {
  gotopost() {}

  render() {
    return (
      <div className="row mt-5">
        {this.props.posts.map(post => {
          return (
            <div className="col-md-6 mb-2" key={post.id}>
              <div className="card">
                <a
                  href={post.link}
                  onClick={this.gotopost.bind(this)}
                  className="btn btn-primary"
                >
                  Go somewhere
                </a>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
}