我有一个非常简单的网站来演示我的问题。
App.js
import React, {useRef, useState, useEffect} from 'react';
import Playaround from './playaround/Playaround';
function App() {
const person = {
name: "joe",
age: 52,
random: {
text: "some random stuff"
}
}
return <Playaround {...person}/>
}
export default App;
Playaround.js
import React, { useState, useEffect, useRef, useReducer, useContext } from "react";
import Proptypes from 'prop-types';
export default function Playaround({name,age,random}) {
return <div>
<h1>{name}</h1>
<h1>{age}</h1>
<h1>{random.text}</h1>
<h1>{random.missing}</h1>
</div>
}
Playaround.propTypes = {
name: Proptypes.string.isRequired,
age: Proptypes.number.isRequired,
random: Proptypes.object.isRequired,
}
如果没有定义名称、年龄或随机性,控制台将发出适当的警告。然而,在";js";,当我放入{random.missing}时,尽管对象random没有密钥";"缺失";,控制台没有发出任何警告。如果重要数据丢失,则很难进行配置。我该如何处理它并让控制台显示警告?
您可以使用PropTypes.shape
并定义random
的形状
Playaround.propTypes = {
name: Proptypes.string.isRequired,
age: Proptypes.number.isRequired,
random: PropTypes.shape({
text: PropTypes.string.isRequired,
missing: PropTypes.string.isRequired
})
}