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

IT技术 javascript reactjs react-native redux
2021-05-25 08:59:48

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

在我连接组件并传递 mapStateToProps 调用后,在函数内部我可以完美地记录状态。但是,当我在组件中使用这个props时,它是未定义的。我在其他组件中使用 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);
2个回答

问题在于,当您调用 时this.tryLogoutthis关键字会动态绑定到事件而不是其component本身,因此该事件没有您正在寻找的props。

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

使用命名箭头函数

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

使用bind方法

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

使用内联箭头函数

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

您可以查看文档中的不同技术:如何将函数绑定到组件实例?

您收到此错误是因为您tryLogout()未绑定到您的组件。所以,this引用不是你的组件。将声明更改为:

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

() => {}被称为arrow function,不绑定你。

小费:

如果为需要访问 anyprop或 的组件构建方法,则需要state将该函数绑定到组件类。当你像我上面那样声明方法时,你就是在绑定它。所以,你的方法将有访问任何可能性propstate您的组件。