React-Native这个prop randomNumberCount在Game中标记为必需,但其值未定义

时间:2017-12-02 11:06:03

标签: react-native

Game.js

    import React from 'react';
    import PropTypes from 'prop-types';
    import {View,Text,StyleSheet} from 'react-native';

这是我的代码,这是警告this prop randomNumberCount is marked as required in Game ,but its value undefined。如何解决这个警告?

class Game extends React.Component {
        static propTypes = {
            randomNumberCount: PropTypes.number.isRequired,
        };
        randomNumbers=Array
        .from({length:this.props.randomNumberCount})
        .map(() =>1+Math.floor(10*Math.random()));
        target=this.randomNumbers
        .slice(0,this.props.randomNumberCount-2)
        .reduce((acc,curr)=>acc+curr,0);

      render() {
        return (
            <View style={styles.container}>
      <Text  style={styles.target}>{this.target}</Text>
          {this.randomNumbers.map((randomNumber,index)=>
            <Text key={index}>{randomNumber}</Text>


            )}

          </View>
        );
      }
    }

1 个答案:

答案 0 :(得分:0)

此警告是因为您已根据原型中的要求标记了 randomNumberCount 。因此,当您使用此组件时,您需要强制传递prop randomNumberCount 。或者您可以从原型声明中删除 .isRequired

您可以将 randomNumberCount 的默认值声明为

static defaultProps = {
    randomNumberCount: dafaultValue
};

供参考: Native Component