将 redux 状态映射到 props 不起作用 [英] mapping redux state to props not working
问题描述
第一次在 react-native 应用上尝试 redux,我遇到了这个问题...
trying for first time redux on a react-native app and i have this problem...
在我连接组件并传递 mapStateToProps 调用后,在函数内部我可以完美地记录状态.但是,当我在组件中使用这个道具时,它是未定义的.我在其他组件中使用 redux 状态就好了...
after i connect the component , and pass a mapStateToProps call, inside the function i can log the state perfectly fine. But, when i use this prop in the component its undefined. I am using the redux state in other component just fine...
谢谢!
import React from 'react';
import { Container, Content, Button,
Text,Card,CardItem,Body,Icon,Header,Left,Right,Title } from 'native-base';
import { connect } from 'react-redux';
class HomeScreen extends React.Component {
static navigationOptions = {
header: null
};
tryLogout(){
console.log(this.props.isLogged);
// UNDEFINED HERE
}
render() {
return (
<Container>
<Header>
<Left></Left>
<Body>
<Title>Menu</Title>
</Body>
<Right>
<Button transparent onPress={this.tryLogout}>
<Icon name='menu' />
</Button>
</Right>
</Header>
<Content padder>
</Content>
</Container>
);
}
}
const mapStateToProps = state => {
console.log(state.isLogged);
// I GET DATA HERE
return {
isLogged: state.isLogged
}
}
export default connect(mapStateToProps,{})(HomeScreen);
推荐答案
问题是在调用this.tryLogout
时,this
关键字被动态绑定到事件而不是 component
本身,因此事件没有您正在寻找的道具.
The problem is that when you are calling this.tryLogout
, the this
keyword is dynamically binded to the event instead of the component
itself, so the event doesn't have the prop that you are looking for.
您可以采取不同的方法来解决这个问题:
You can take different approaches on how to solve this:
使用命名箭头函数
tryLogout = () => console.log(this.props)
...
onPress={this.tryLogout}
使用bind
方法
Using the bind
method
onPress={this.tryLogout.bind(this)}
使用内联箭头函数
onPress={() =>this.tryLogout()}
.
您可以查看文档中的不同技术:如何将函数绑定到组件实例?
You can take a look to the different techniques in the docs: How do I bind a function to a component instance?
这篇关于将 redux 状态映射到 props 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!