【发布时间】:2017-08-08 05:37:37
【问题描述】:
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);
这个组件有一个 prop logList,它是在页面加载时从服务器获取的。它的初始值为 [],几秒钟后它有大约 80 个对象。它的值是使用 redux 设置的。
在上面的代码中,当logList 属性发生变化时,componentDidUpdate 方法被触发并且this 的值发生变化,因此我无法在scrollLogs 方法中访问this.props.logList,该方法在触发时触发滚动一个 div。
this.props.logList 在scrollLogs 中始终是空数组。在 componentDidUpdate 方法中正确打印所有 80 个对象
正如您可能已经猜到的那样,window.a == this 打印出false。
如何在scrollLogs 中访问this.props.logList?
【问题讨论】:
-
你能说明
scrollLogs是如何被调用的吗? -
另外,从 JSX 模板发布组件的初始化代码。 props 是如何传入的等等。
-
我已经用更多信息更新了我的问题
-
你为什么还要关心 React 中
this的值呢?顺便说一句,您应该检查componentDidMount和componentWillUnmount。如果您隐藏该组件然后再次显示它,它将是一个不同的组件。 -
我不关心
this,但我确实关心this.props.logList,它是一个空数组,因为它的值在组件安装阶段是一个空数组。