React Native App中的“undefined不是对象”错误

时间:2018-03-26 05:40:15

标签: node.js reactjs react-native jsx react-proptypes

我是React Native和Expo XDE的新工作,我在类型arrayOf的TaskList.js文件中实现PropTypes但是在编译应用程序时我得到一个错误,指示“undefined不是一个对象(评估' react3.default.PropTypes.arrayOf')“即使我添加另一个类型为String的PropTypes或其他同样的事情发生。

如何使用PropTypes解决此问题?

错误

error

的package.json

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "1.11.1",
    "jest-expo": "25.0.0",
    "react-test-renderer": "16.2.0"
  },
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
  "start": "react-native-scripts start",
  "eject": "react-native-scripts eject",
  "android": "react-native-scripts android",
  "ios": "react-native-scripts ios",
  "test": "node node_modules/jest/bin/jest.js"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "expo": "^25.0.0",
    "react": "16.2.0",
    "react-native": "0.52.0"
  }
}

App.js

import React from 'react';
import { StyleSheet, Text, View, ListView } from 'react-native';
import TaskList from './TaskList';

export default class App extends React.Component {
  constructor(props, context){
    super(props, context);

    this.state = {
      todos:[
        {
          task : "Learn React Native"
        },
        {
          task : "Learn Redux"
        },
     ]
    }

  }

  render() {
    return (
      <View style={styles.container}>
        <TaskList todos={this.state.todos}/>
     </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

TaskList.js

import React, {Component, PropTypes} from 'react';
import {View, Text, Button, ListView} from 'react-native';

class TaskList extends React.Component {
  constructor(props, context){
    super(props, context);

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !==   r2});

    this.state = {
      dataSource: ds.cloneWithRows(props.todos),
    }

  }

  renderRow =(todo)=>{
    return(
      <Text>{todo.task}</Text>
    )
  }

  render(){
    return(
      <View>
        <ListView
          dataSource={this.state.dataSource}
          key={this.props.todos}
          renderRow={this.renderRow.bind(this)}
        />
      </View>
   )
  }
}

TaskList.propTypes = {
  todos: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
}

export default TaskList;

2 个答案:

答案 0 :(得分:2)

PropTypes已移入其单独的NPM包(v15 +),prop-types,并且不再存在于React包中。这就是它被报告为import PropTypes from 'prop-types'; 的原因。安装并导入:

.CSV

答案 1 :(得分:1)

您需要添加依赖项

npm install --save prop-types

此命令在项目中安装prop-types。检查项目中的package.json文件

 "dependencies": {
    "prop-types": "^15.6.1"
 }

并将其导入您要使用的项目中。通过导入以下包

import PropTypes from 'prop-types'; // ES6