【问题标题】:Failed prop type: The prop `options` is marked as required in `signupCheckBoxes`, but its value is `undefined`失败的道具类型:道具`options`在`signupCheckBoxes`中标记为必填,但其值为`undefined`
【发布时间】:2019-12-24 08:12:06
【问题描述】:

当我收到这个错误时,我正在创建一个 react-native 组件..

Failed prop type: The prop `options` is marked as required in `signupCheckBoxes`, but its value is `undefined`.

基本上,我正在做的是传递一个数组,其中包含我要渲染的对象的类型

const inputFields = [
  {
    key: 'dob', 
    type: 'dateTyper', //change this to Dob component
    label: 'Your Date of birth',
    helper: 'Your Birthdate will help us in connecting you with people of similar age',
    required: true
  }, 
  {
    key: 'gender', 
    type: 'checkboxes', 
    label: 'Gender',
    required: true, 
    templateOptions: {
      multipleSelect: true,
      options: ['Male', 'Female', 'Others']
    }
  ]

然后在用户遍历数组时映射组件

   export const SignupFormComponent = (props) => {
        const {
        keyboardAutoOpenForText, 
        inputFields, 
        buttonStyle, 
        ProgressBarProps,  
        backgroundViewColor, 
        defaultColor, 
        helperTextStyle, 
        globalButtonText,
        buttonTextStyle,
        textStyle,
        onButtonClick,
        errorStyle,
        defaultErrorMessage
      } = props
           // All the component 
  const [index, setIndex] = useState(0)
  const [payload, setPayloadData] = useState({})
  const [Loading, toggleLoadingData] = useState(false)
  const [Error, setErrorData] = useState({status: false, message: ''})
  // Current Component based on indux
  const currentComponent = inputFields[index]
  const {key, type, label, helper, buttonText} = currentComponent
  const templateOptions =  currentComponent.templateOptions || {}
  // if no template options, initlalize an empty object
  const {number, placeHolder, templateStyle, options}  = templateOptions
  const usedButtonText =  buttonText || globalButtonText
  // Setting up/mutating props 

  // --- Progress bar ---
  ProgressBarProps.currentProgress = index 
  ProgressBarProps.totalNumberOfProgressBars = inputFields.length
  ProgressBarProps.colorOfProgressBar = ProgressBarProps.colorOfProgressBar || defaultColor

  const onChangeHandler = (data, errorMessage=null) => {
    if (!errorMessage) {
      const currentData = {...payload}
      currentData[key] = data
      setPayloadData(currentData)
    } else {
      setErrorData({status: true, message: errorMessage})
    }
  }

  const getValueFromState  = async () => {
    setErrorData({status: false, message: ''})
    toggleLoadingData(true)
    const currentValue = payload[key]
    try {
      const eventTrack = await onButtonClick(index, key, currentValue, payload)
      if (index < inputFields.length) setIndex(index + 1)
      return toggleLoadingData(false)
    } catch (error) {
      if (error.message) setErrorData({status: true, message: error.message})
      else setErrorData({status: false, message: defaultErrorMessage})
      return toggleLoadingData(false)
    }
  }


          const mapSignUpComponents = {
            text: (
                <TextInput  
                  placeholder={placeHolder}
                  number={number}
                  style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, templateStyle]}
                  onChangeText={text => onChangeHandler(text)}
                  value={payload[key] ? `${payload[key]}` : ''} // Doesn't seem right but otherwise the value of the text input also get mutate with other values
                />),
            dateTyper: (
              <DateTyper
              textInputStyle={[{color: defaultColor, width: (Dimensions.get('window').width * 0.6)/8 }, styles.nextInputStyle, templateStyle]} 
              upsideEmit={onChangeHandler}/>
            ),
            checkboxes: (
              <CheckBoxes 
              options={options}
              />
            )
          }


          const renderComponent = mapSignUpComponents[type]
          return (
               <View> 
               {renderComponent}
             <View>
          )
    }

最初,组件应该是 dateTyper (const renderComponent = mapSignUpComponents[type]),所以 options 键甚至不是必需的,因此选项是 undefined

optionscheckboxes 组件的必需属性,但由于我们没有渲染它,我不确定为什么会出现上述错误

如果有人能帮助我解决同样的问题,我将不胜感激。

我的复选框组件看起来像这样

import React, {useState} from 'react'
import PropTypes from 'prop-types'
import { CheckBox } from 'react-native-elements'
import { View, Text } from 'react-native'

const signupCheckBoxes = (props) => {
  const { options, multipleSelect} = props
  console.log(options)
  return (
    <View>
    <Text> Hello</Text>

    </View>
  )
}

signupCheckBoxes.propTypes = {
  options: PropTypes.array.isRequired,
  multipleSelect: PropTypes.bool
}

signupCheckBoxes.defaultProps = {
  multipleSelect: true
}



export default signupCheckBoxes

【问题讨论】:

  • 如果你运行代码,你会从singupCheckBoxes得到一些日志吗?我认为signupCheckBoxes 在某处呈现。
  • templateOptions 似乎在输入字段对象内。我认为您无法访问这样的选项,这就是它给出未定义的原因
  • @YonggooNoh 不,看不到任何日志(在signupCheckBoxes 中添加了控制台日志,但这些日志没有记录)
  • @warmachine 抱歉,无法理解您的评论
  • const {number, placeHolder, templateStyle, options} = templateOptions;你能在这行之后安慰你得到了什么吗?

标签: javascript reactjs


【解决方案1】:

即使options 未定义,您似乎也在执行&lt;CheckBoxes options={options} /&gt;。这基本上转化为初始化该组件(但不调用渲染函数)。在初始化期间,react 将检查所有必需的 props 是否可用,然后抛出错误。

要修复它,我会执行以下操作:

const mapSignUpComponents = {
            text: (
                <TextInput  
                  placeholder={placeHolder}
                  number={number}
                  style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, templateStyle]}
                  onChangeText={text => onChangeHandler(text)}
                  value={payload[key] ? `${payload[key]}` : ''} // Doesn't seem right but otherwise the value of the text input also get mutate with other values
                />),
            dateTyper: (
              <DateTyper
              textInputStyle={[{color: defaultColor, width: (Dimensions.get('window').width * 0.6)/8 }, styles.nextInputStyle, templateStyle]} 
              upsideEmit={onChangeHandler}/>
            ),
            checkboxes: options === undefined ? undefined : (
              <CheckBoxes 
              options={options}
              />
            )
          }

我希望这会有所帮助!

【讨论】:

  • 有没有关于组件初始化的文档或文章?
  • 我不这么认为。我通过查看生成的 JS 代码(来自 JSX 文件)发现了这种行为。
猜你喜欢
  • 2018-01-24
  • 2022-01-05
  • 2019-05-21
  • 2020-01-14
  • 2019-07-15
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多