鍍金池/ 問答/HTML/ 【已解決】React 調用函數(shù)竟然不對,提示這個函數(shù)undefined

【已解決】React 調用函數(shù)竟然不對,提示這個函數(shù)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>)
        }
    }

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

回答
編輯回答
入她眼

goToDetail函數(shù)倒是綁定了this,是renderComment 函數(shù)出問題了么?

2017年12月11日 21:45
編輯回答
笑浮塵

goToDetail函數(shù)是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做遍歷的時候,會根據(jù)data-reactid生成虛擬dom樹。如果你沒有手動的添加unique key的話,react是無法記錄你的dom操作的。它只會在重新渲染的時候,繼續(xù)使用相應dom數(shù)組的序數(shù)號(就是array[index]這種)來比對dom樹。

推薦您看一下如何正確地在React中處理事件:
官網英文文檔:https://reactjs.org/docs/hand...
中文文檔:如何正確地在React中處理事件 (滾動到“如何正確地在React中處理事件”或者搜索“如何正確地在React中處理事件”

希望對您有所幫助!

2018年3月21日 23:33
編輯回答
櫻花霓

之前還沒人回答的時候,我就已經知道哪錯了,刪也刪不了。只能硬著頭皮在這掛著了
招誰惹誰了,怎么還踩了我一下,醉了

2017年12月15日 04:19
編輯回答
失魂人

哪個函數(shù)undefined?

2018年7月10日 10:09
編輯回答
我以為

手動綁定下this

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

用箭頭函數(shù)

renderComment = () => {}
2017年7月8日 15:59