【问题标题】:Failed prop type: The `` is marked as required in ``, but its value is `undefined`失败的道具类型:``在``中标记为必需,但其值为`undefined`
【发布时间】:2019-02-16 19:48:58
【问题描述】:

我正在使用流并从另一个组件传递状态。我正在使用 proptypes 和 statetypes。我该如何解决这个错误?警告:道具类型失败:提供给RoiCalculatorstring 类型的无效道具business_size,应为number。 在 RoiCalculator 中

webpack/roi_calculator/main.jsx

 export type StateType = {
  business_size: number,
  organisation_name: string,
  pay_period: boolean,
  timesheet_savings: number,
  roster_optimisation: number,
  reduction_time: number,
  elimination_award: number,
  annual_savings: number,
  annual_subscription: number,
  roi: number,
}

export type PropsType = {
  business_size: number,
  organisation_name: string,
  pay_period: boolean,
  timesheet_savings: number,
  roster_optimisation: number,
  reduction_time: number,
  elimination_award: number,
  annual_savings: number,
  annual_subscription: number,
  roi: number,
}

export default class RoiCalculator extends 
 React.Component<PropsType, StateType> {
 constructor (props: PropsType) {
   super(props)
   this.state = {
     business_size: this.props.business_size,
     organisation_name: this.props.organisation_name,
     pay_period: this.props.pay_period,
     timesheet_savings: 0,
     roster_optimisation: 0,
     reduction_time: 0,
     elimination_award: 0,
     annual_savings: 0,
     annual_subscription: 0,
     roi: 0,
   }
 }

<RoiAssumptions results={this.state}/>

webpack/roi_calculator/views/RoiAssumptions/index.jsx

export type PropsType = {
  business_size: number,
  organisation_name: string,
  pay_period: boolean,
  timesheet_savings: number,
  roster_optimisation: number,
  reduction_time: number,
  elimination_award: number,
  annual_savings: number,
  annual_subscription: number,
  roi: number,
}
 const t = (key, ...args) => globalT(`js.roi_calculator.${key}`, ...args)

export default class RoiAssumptions extends 
React.Component<PropsType, StateType> {
  constructor (props: PropsType) {
     super(props)
  }

        <div className={styles.aside__value}>
          <p>$ 
{this.roundOffResult(this.props.results.timesheet_savings)}</p>      
        </div>

【问题讨论】:

  • this.props.business_size 第一次设置在哪里?看起来它以某种方式获得了一个字符串值。如果它来自某种后端 API,则需要在将其作为道具传递之前将其转换为数字。

标签: reactjs flowtype


【解决方案1】:

鉴于标题中建议的错误(必填字段的值为undefined)和问题中的错误(无效类型string,预期number)略有不同,我将尝试为后者提供解决方案.我会寻找呈现RoiCalculator 的任何地方,检查business_sizeprop 是否没有作为字符串传递。例如下面的 sn-ps 会违反 prop 类型检查:

<RoiCalculator business_size="30" {...otherProps}/>
<RoiCalculator business_size={"30"} {...otherProps}/>

然而这将是正确的

<RoiCalculator business_size={30} {...otherProps}/>

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2018-01-24
    • 2022-01-05
    • 2019-05-21
    • 2020-01-14
    • 2019-07-15
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多