2017-08-08 122 views
-2
class Log extends React.Component{ 
    constructor(props){ 
     super(props); 

     this.scrollLogs = this.scrollLogs.bind(this); 
     window.a = this; 
    } 

    componentDidUpdate(){ 
     console.log("componentDidUpdate this.props.logList", this.props.logList, window.a == this); 
    } 

    scrollLogs(e){ 
     console.log("this.props.logList", this.props.logList); 
    } 



    render(){ 
     return (<div className="logs"> 
      ... 
      <div className="log-list" onScroll={this.scrollLogs}> 
      {this.props.logList.map((l, i) => { 
       return (
        ... 
       ); 
      })} 
      </div> 
     </div>); 
    } 
} 


var mapStateToProps = (state, ownProps) => { 
    return { 
     logList: state.logs 
    }; 
} 

var mapDispatchToProps = (dispatch, ownProps) => { 
    ... 
} 

export var LogContainer = connect(mapStateToProps, mapDispatchToProps)(Log); 

该组件具有一个道具logList,它在页面加载时从服务器获取。它的初始值是[],几秒钟后就会有大约80个对象。它的值是使用redux设置的。当'道具'发生变化时'this'发生变化

在当支柱logList改变componentDidUpdate方法得到射击和this的值更改上面的代码,因此,我无法访问this.props.logListscrollLogs方法中,当滚动一个div其被烧制。

this.props.logListscrollLogs里面总是空的数组。所有80个物体都可以正确打印componentDidUpdate方法

正如您可能猜到的window.a == this打印false

如何在scrollLogs内访问this.props.logList

+2

你可以显示如何调用scrollLogs吗? –

+0

也可以从JSX模板发布组件的初始化代码。道具是如何通过的等等 – Denialos

+0

我已更新我的问题并提供更多信息 –

回答

0

最后,我发现了这个问题。我正在使用webpack“热模块替换”功能(没有提到这个问题,因为我不知道它很重要)。它正在重新加载我的反应组件,因为它突变了this的值,因此当我尝试访问this.props.logList时,scrollLogs中的代码正在访问旧的this,该代码没有新的logList

0

我假设你的组件是这样的:

<Parent> 
    <Log logList={ this.props.logList } /> 
</Parent> 

this.props.logList是从你的终极版商店。当您店中的logList发生更改时,您的<Log />组件中的道具也会发生变化,并使其重新呈现。这就是触发componentDidMount的原因,如果您正确触发scrollLogs(e),则this.props.logList的值也会发生变化。尝试拨打电话render

class Log extends React.Component{ 
    ... 
    render() { 
     this.scrollLogs() 
     return <div /> 
    } 
} 
相关问题