this.ops在使用redux时给出未定义的



我是redux的新手。我已经通过mapStateToProps传递了一个值,而this.propsrender()中具有值。然而,如果我像下面例子中的renderRow函数一样在函数中控制台this.props,它会给出undefined。为什么会出现这种情况?

constructor() {
super();
}
renderRow(rowData) {
//this.console gives undefined why
console.log('props1', this.props);
}
render() {
//this.props has value here
{console.log('props1', this.props)}
return (
<View style={styles.container}>
<ListView
dataSource={this.dataSource}
renderRow={this.renderRow}
/>
</View>
); 
}
const mapStateToProps = state => {
return {selectionsList: state.selections, 
selectionId: state.selectionId};
}

原因是您将一个函数传递给另一个组件,而这个函数不再绑定到您的类实例。只有当你用左边的实际对象调用它(而不是传递(时,它才有它——你可以在我的文章中阅读更多关于这一点的内容。这里有几个解决方案,您可以在有关事件处理的文档中阅读这些解决方案。这是添加事件处理程序时的常见模式。

因此,您可以执行以下操作:

  1. 使用类属性:

    renderRow=(rowData(=>{console.log("道具1",this.props(;}

如果您以这种方式使用它,它将自动将您的函数绑定到您的实例。

  1. 当您通过回调时,只需创建一个新的箭头函数:

    <ListView
    dataSource={this.dataSource}
    renderRow={(data) => this.renderRow(data)}
    />
    

Arrow函数没有自己的this,因此它可以正常工作。

  1. 当您将方法作为属性传递时,您可以绑定它。它的工作方式与前一个几乎相同——每次渲染时,我们都会创建一个新函数:

    <ListView
    dataSource={this.dataSource}
    renderRow={this.renderRow.bind(this)}
    />
    
  2. 在构造函数中绑定。你可以在构造函数中绑定它——它会在实例化时创建一个新函数,所以你不会每次重新渲染都这样做。它的工作原理与第一个类似,但更明确(也更详细(:

    constructor(props) {
    super(props);
    this.renderRow = this._renderRow.bind(this);
    }
    _renderRow(data) {
    console.log('props1', this.props);
    }
    

我个人认为,只要使用第一种方法,它就足够常见和稳定(这是提案中的第三阶段(。

最新更新