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