【已解决】React 调用函数竟然不对,提示这个函数undefined

goToDetail(){
        console.log("看看能出来吗?")
    }
    renderComment({name, author,uploadTime,description,category,sraID}) {
        switch (category){
            case "0":return "other";
            case "1":return "project";
            case "2":return "paper";
            case "3":return "book";
            case "4":return "certificate";
            case "5":return "patent";
            case "6":return "picture";
        }
        return (
            <li className="listLi">
                <h3 className="listTitle" onClick={this.goToDetail.bind(this)}><a>{name}</a></h3>
                <p>
                    <span>{author}</span>
                    <span> - </span>
                    <span>{uploadTime}</span>
                </p>
                <p><span>描 述:</span>{description}</p>
            </li>
        );
    }
    render(){
        if(this.state.contents){
            return(<div className="main_div">
                <LitNav />
                <ul className="lists">{this.state.contents.map(this.renderComment)}</ul>
            </div>)
        }else{
            return(<div className="main_div">
                <LitNav />
            </div>)
        }
    }

不知道什么原因,求大神解答。。。

阅读 5.9k
5 个回答

goToDetail函数是undefined,修改如下代码即可:

{this.state.contents.map((item) => this.renderComment(item))}

以上代码应该还有一个错误:Warning: Each child in an array or iterator should have a unique "key" prop

原因是在react遍历时,需要在子元素上加上unique key。这个是和react的dom-diff算法相关的。react对dom做遍历的时候,会根据data-reactid生成虚拟dom树。如果你没有手动的添加unique key的话,react是无法记录你的dom操作的。它只会在重新渲染的时候,继续使用相应dom数组的序数号(就是array[index]这种)来比对dom树。

推荐您看一下如何正确地在React中处理事件:
官网英文文档:https://reactjs.org/docs/hand...
中文文档:如何正确地在React中处理事件 (滚动到“如何正确地在React中处理事件”或者搜索“如何正确地在React中处理事件”

希望对您有所帮助!

手动绑定下this

constructor() {
    super();
    this.renderComment = this.renderComment.bind(this);
}

用箭头函数

renderComment = () => {}

哪个函数undefined?

goToDetail函数倒是绑定了this,是renderComment 函数出问题了么?

之前还没人回答的时候,我就已经知道哪错了,删也删不了。只能硬着头皮在这挂着了
招谁惹谁了,怎么还踩了我一下,醉了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题