React Native Button导致Invariant无效

时间:2016-12-01 03:35:54

标签: react-native react-native-button

对于我的生活,我无法弄清楚为什么这一小段代码不起作用!

我已将问题与Button元素隔离开来(导入语句似乎很好)。

我看到错误“不变违规:元素类型无效:期望一个字符串(用于内置组件)或一个类/函数(用于复合组件)但得到:undefined。检查Login的render方法。< / p>

 import React, { ScrollView, Image, StyleSheet, Button } from "react- 
 native";
 import { connect } from "react-redux/native";

 const onButtonClicked = () => {};

class Login extends React.Component {
componentDidMount() {}

render() {
    return (
        <ScrollView
            style={{ flex: 1 }}
            contentContainerStyle={{
                justifyContent: "center",
                alignItems: "center"
            }}
        >
            <Image
                source={require("../../img/coin.png")}
                resizeMode={Image.resizeMode.cover}
                style={Styles.coinLogo}
            />

            <Button title="Login default" onPress={() => {}} />
        </ScrollView>
      );
   }
}

Login.propTypes = {
  dispatch: React.PropTypes.func
};

Login.defaultProps = {
   dispatch: () => {}
};

const Styles = StyleSheet.create({
   coinLogo: {
     marginTop: 50,
     height: 200,
     width: 200
},
loginButton: {
    marginTop: 50
}
});

export default connect(state => ({}))(Login);

1 个答案:

答案 0 :(得分:2)

这是一个令人讨厌的问题,因为错误消息真的很模糊。它必须(我认为)与对象解构。

当您对一个物体进行构造时,请说:

var myObject = {a: 1, b: 2, c: 3};

let {a, b, c, d} = myObject;

您的发布者会执行以下操作:

 let a = myObject.a;
 let b = myObject.b;
 let c = myObject.c;
 let d = myObject.d; // Ah! But we never defined a 'd' key, did we?

当然,不存在的密钥会在不引发错误的情况下评估为undefined,因此您得到的是d,其值为undefined

让我们回到你的进口。我认为他们应该是这样的:

import React from 'react'; // The React API moved to the react package, you should be getting an error because of this. See https://github.com/facebook/react-native/releases/tag/v0.26.0 (Unless you are using React Native <= 0.25)
import { ScrollView, Image, StyleSheet, Button } from "react-native";
import { connect } from "react-redux"; // As far as I know, the connect is exported directly from 'react-redux', but it might be OK the way you had it.

现在,让我们转到您的render。我们正在尝试呈现ScrollViewImageButton。 RN正在提出错误,因为其中一个被评估为undefined,这是不允许的,但它没有告诉我们哪一个。您可以尝试console.log三者的值并检查哪一个未定义。但是,我强烈认为它是Button,因为它已添加到RN 0.37中,正如我之前在导入React中所提到的那样,您必须运行以前版本的RN 0.26.0标签,否则代码会产生不同的错误。

如果是这样,请告诉我。