【问题标题】:'this' changes when 'props' changes'props' 改变时'this' 改变
【发布时间】: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.logListscrollLogs 中始终是空数组。在 componentDidUpdate 方法中正确打印所有 80 个对象

正如您可能已经猜到的那样,window.a == this 打印出false

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

【问题讨论】:

  • 你能说明scrollLogs是如何被调用的吗?
  • 另外,从 JSX 模板发布组件的初始化代码。 props 是如何传入的等等。
  • 我已经用更多信息更新了我的问题
  • 你为什么还要关心 React 中 this 的值呢?顺便说一句,您应该检查componentDidMountcomponentWillUnmount。如果您隐藏该组件然后再次显示它,它将是一个不同的组件。
  • 我不关心this,但我确实关心this.props.logList,它是一个空数组,因为它的值在组件安装阶段是一个空数组。

标签: reactjs redux


【解决方案1】:

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

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

this.props.logList 来自您的 redux 商店。当您的 logList in store 发生变化时,您的 &lt;Log /&gt; 组件中的道具也会发生变化,这会使其重新渲染。这就是触发componentDidMount 的原因,如果您正确触发scrollLogs(e)this.props.logList 的值也会发生变化。尝试拨打render

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2018-12-04
      相关资源
      最近更新 更多