0

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

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

我看到错误“不变违规:元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。检查登录的渲染方法。

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

1 回答 1

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. 我们正在尝试渲染 a ScrollView、 aImage和 a Button。RN 提出错误是因为其中一个被评估为undefined,这是不允许的,但它并没有告诉我们是哪一个。您可以尝试console.log这三个的值并检查哪个未定义。但是,我强烈认为它是Button,因为它是在RN 0.37中添加的,并且正如我之前在 import 中提到的React,您必须运行 0.26.0 标签之前的 RN 版本,否则代码会引发不同的错误。

让我知道是否是这种情况。

于 2016-12-01T07:17:37.103 回答