当'道具'发生变化时'this'发生变化
问题描述:
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.logList
在scrollLogs
方法中,当滚动一个div其被烧制。
this.props.logList
在scrollLogs
里面总是空的数组。所有80个物体都可以正确打印componentDidUpdate
方法
正如您可能猜到的window.a == this
打印false
。
如何在scrollLogs
内访问this.props.logList
?
答
最后,我发现了这个问题。我正在使用webpack“热模块替换”功能(没有提到这个问题,因为我不知道它很重要)。它正在重新加载我的反应组件,因为它突变了this
的值,因此当我尝试访问this.props.logList
时,scrollLogs
中的代码正在访问旧的this
,该代码没有新的logList
。
答
我假设你的组件是这样的:
<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 />
}
}
你可以显示如何调用scrollLogs吗? –
也可以从JSX模板发布组件的初始化代码。道具是如何通过的等等 – Denialos
我已更新我的问题并提供更多信息 –