gpt4 book ai didi

javascript - 将 redux 状态映射到 props 不起作用

转载 作者:行者123 更新时间:2023-12-03 01:34:19 25 4
gpt4 key购买 nike

第一次尝试在react-native应用程序上进行redux,我遇到了这个问题......

在我连接组件并传递 mapStateToProps 调用后,在函数内部我可以完美地记录状态。但是,当我在组件中使用这个属性时,它是未定义的。我在其他组件中使用 redux 状态就好了......

谢谢!

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 关键字会动态绑定(bind)到事件,而不是 component 本身,因此该事件没有您正在寻找的 Prop 。

您可以采取不同的方法来解决此问题:

使用命名箭头函数

tryLogout = () => console.log(this.props)
...
onPress={this.tryLogout}

使用bind方法

onPress={this.tryLogout.bind(this)}

使用内联箭头函数

onPress={() => this.tryLogout()}

您可以查看文档中的不同技术:How do I bind a function to a component instance?

关于javascript - 将 redux 状态映射到 props 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51145511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com