反应本机按钮导致不变无效

React Native Button causing Invariant Invalid

我这辈子都搞不懂为什么这段代码不起作用!

我已将问题隔离到 Button 元素(导入语句似乎没问题)。

我看到错误“Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. 检查渲染方法登录。

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

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

当你解构一个对象时,说:

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 标签之前,否则代码会引发不同的错误。

如果是这样请告诉我。