开发者问题收集

react native TypeError:TypeError:未定义不是一个对象(评估'_this.state.cartAmount')

2019-02-15
9408

在 App.js 中,如果我在 tabBarComponent 中分配 this.state.cartAmount ... 则会出现错误

TypeError: TypeError: undefined is not an object (evaluating'_this.state.cartAmount')

在此处输入图像描述

如果我将 tabBarComponent 设置为

{(this.state != null) ? this.state.cartAmount : '0.0'}

并点击 tabBarComponent 中的 TouchableOpacity Home,则会出现错误,即使我编写箭头函数也是如此

HandleTabPressOne = () => {
    this.setState({ cartAmount: '12.20' });
}

我认为构造函数中存在一些问题,请指导

在此处输入图片描述

const TabNavRoutes = createBottomTabNavigator({
    Tab1: {screen: HomeScreenStack},
    Tab2: {screen: Screen2},
    Tab3: {screen: Screen3},
    Tab4: {screen: Screen4}
   },
   {
    tabBarComponent:({navigation}) => (
      <View style={{flex: 0.1, backgroundColor: '#FF0000', borderColor: '#FF0000', borderWidth: 1}}>
                <View style={{flexDirection:'row', justifyContent: 'space-around', alignItems: 'center', paddingTop: 5}}>

                    <TouchableOpacity onPress={() => this.HandleTabPressOne.bind() } style={{alignItems: 'center', marginLeft: 5}}>
                        <Text style={styles.textFAB}>Home</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => navigation.navigate('Tab2')}style={{alignItems: 'center'}}>

                        <Text style={styles.textFAB}>History</Text>
                    </TouchableOpacity>
                    <View style={styles.cartFAB}>
                        <MaterialIcons name="shopping-basket" size={24} color="#FFFFFF" style={{marginTop: 10}} />
                        <Text style={styles.totalCart}>{ this.state.cartAmount} €</Text>
                    </View>
                </View>
            </View>
   )});

const AppSwitchNavigator = createSwitchNavigator({
  Welcome: { screen: splashScreen },
  Dashboard: { screen: TabNavRoutes }
});

const AppContainer = createAppContainer(AppSwitchNavigator);

export default class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      cartAmount: '18.50'
    }
  }

  HandleTabPressOne() {

    this.setState({ cartAmount: '12.20' });
    alert(this.state.cartAmount)
  }

  render() {
      return <AppContainer/>
  }
}
2个回答
() => this.HandleTabPressOne.bind()

这里有 2 个绑定。您应该使用箭头或绑定。尝试以下方法:

<TouchableOpacity onPress={this.HandleTabPressOne}

您的方法可以使用箭头绑定

HandleTabPressOne = () => {
  this.setState({ cartAmount: '12.20' });
  alert(this.state.cartAmount)
}
ageoff
2019-02-15
(this.state != null && this.state !== undefined) ? this.state.cartAmount : '0.0'}
gandalf
2019-02-15