【问题标题】:mapping redux state to props not working将 redux 状态映射到 props 不起作用
【发布时间】:2018-07-03 01:30:18
【问题描述】:

在 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);

【问题讨论】:

  • 您的代码应该可以正常工作。随便碰碰运气,介意分享一下combineReducers的方法吗?

标签: javascript reactjs react-native redux


【解决方案1】:

问题是当您调用this.tryLogout 时,this 关键字被动态绑定到事件而不是component 本身,因此事件没有您要查找的道具。

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

使用命名箭头函数

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

使用bind 方法

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

使用内联箭头函数

onPress={() =&gt; this.tryLogout()}.

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

【讨论】:

    【解决方案2】:

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

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

    () =&gt; {},称为arrow function,为您执行绑定。

    提示:

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

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 2018-09-13
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多