React native 使用redux时,this.props提供未定义的

React native 使用redux时,this.props提供未定义的,react-native,react-redux,React Native,React Redux,我是新手。我已经通过mapStateToProps传递了一个值,并且这个.props在render()中有值。但是,如果我在函数中控制台this.props,就像下面示例中的renderRow函数一样,它会给出未定义的。为什么会这样 constructor() { super(); } renderRow(rowData) { //this.console gives undefined why console.log('props1', this.props); }

我是新手。我已经通过
mapStateToProps
传递了一个值,并且
这个.props
render()
中有值。但是,如果我在函数中控制台
this.props
,就像下面示例中的
renderRow
函数一样,它会给出未定义的。为什么会这样

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};
}
constructor(){
超级();
}
renderRow(行数据){
//此.console给出了未定义的原因
console.log('props1',this.props);
}
render(){
//这个.props在这里有价值
{console.log('props1',this.props)}
返回(
); 
}
常量mapStateToProps=状态=>{
返回{selectionsList:state.selections,
selectionId:state.selectionId};
}

原因是您将一个函数传递给另一个组件,而该函数不再绑定到您的类实例。只有在调用它(而不是传递)时,它才具有左侧的实际对象–您可以在中阅读更多内容。这里有几种解决方案,您可以在中阅读。这是添加事件处理程序时的常见模式

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

  • 使用类属性:

    renderRow=(行数据)=>{ console.log('props1',this.props); }

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

  • 传递回调时,只需创建一个新的arrow函数:

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


  • 我个人会说,只使用第一种方法,它非常常见且足够稳定(这是提案中的第3阶段)。

    像这样绑定renderRow方法。{this.renderRow.bind(this)}构造函数中的
    bind
    renderRow
    函数或将其转换为
    arrow
    函数,如
    renderRow=(rowData)=>{…}
    <ListView
        dataSource={this.dataSource}
        renderRow={this.renderRow.bind(this)}
    />
    
    constructor(props) {
      super(props);
    
      this.renderRow = this._renderRow.bind(this);
    }
    
    _renderRow(data) {
       console.log('props1', this.props);
    }