簡體   English   中英

React Context API Consumer塊中的調試器 - 這是未定義的

[英]Debugger inside React Context API Consumer block - this is undefined

我正在嘗試使用瀏覽器開發工具中的render方法中的Context API Consumer來調試組件。 如果我在Consumer塊中放置斷點,我不能動態地在控制台上打印道具等,因為thisundefined 通常運行它工作正常,但在調試時只有this值是undefined 以下是組件的示例呈現方法。

  componentMethod = () => {
      console.log(this.props.name); //Placing breakpoint here, value is this is defined
  }

  render() {
        return (
            <div className={styles.container}>
                <div>
                    <h4>{this.props.name}</h4>
                </div>
                <div className={styles.block}>
                    <MyComponent.Consumer>
                        {
                            ({ firstParam, secondParam }) =>
                                <AotherComponent
                                    firstParam={firstParam}
                                    secondParam={secondParam}
                                    thirdParam={this.props.name}
                                />
                        }
                    </MyComponent.Consumer>
                </div>
            </div>
        )
  }

我可以在這里使用胖箭頭,但是我可以在componentMethod使用斷點來獲得這個值。 有沒有辦法將它bind this Consumer塊?

試試這個,但是,你的問題沒有提供你想要解決的問題的足夠背景。 如果您共享Provider實現以及使用它的位置會更好。

render() {
        const { name } = this.props;
        return (
            <div className={styles.container}>
                <div>
                    <h4>{name}</h4>
                </div>
                <div className={styles.block}>
                    <MyComponent.Consumer>
                        {
                            ({ firstParam, secondParam }) =>
                                <AotherComponent
                                    firstParam={firstParam}
                                    secondParam={secondParam}
                                    thirdParam={name}
                                />
                        }
                    </MyComponent.Consumer>
                </div>
            </div>
        )
  }

看起來您有興趣了解您的消費者在執行期間傳遞給您的組件的內容。 有兩種方法可以實現它。

艱辛的道路

讓我們分析消費者的工作方式(使用您的樣本)。 這可能有助於您找到正確的調試位置。

render()方法中,您有一個<MyComponent.Consumer>調用。 新的Context Consumer API構建在render-prop模式上

關於render-prop模式需要記住的重要一點是:它是一個function調用。 此函數應返回在渲染樹時可以考慮的內容。

由於它是一個函數調用,您可以將console.log語句放在元素之前。 您必須添加一個顯式的return語句。

至於為什么它在你的方法中是undefined的。 我假設componentMethod不是生命周期方法,因此有可能是thisthis.props是基於你如何調用該方法不明確的。 我沒有在渲染方法中的任何地方看到它被調用。

Eas(y / ier)方式:

使用react dev工具瀏覽器擴展。 您可以按名稱查找所有組件。 點擊它們你可以看到道具和狀態,甚至是上下文(據我記得)。 你甚至可以改變的值,看看反應的反應吧!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM