Intermédiaire
Quel(s) est(sont) le(s) problème(s) dans ce code ?
function SomeComponent(props) {
if (props.condition) {
props.condition = !props.condition;
} else {
return (
<p>Bonjour,</p>
<p>Je suis développeur React.js</p>
)
}
}
Modifier
2
Évaluations de la communauté
Omar EL MANSSOURI
03/09/2024
Problems Explained:
1. "Props are modified":
Problem: The code changes props.condition directly with props.condition = !props.condition. In React, you should never modify props directly because they are meant to be read-only. Props should be set by the parent component and should not be changed within the child component.
2. "The function does not return Virtual DOM if props.condition is true":
Problem: If props.condition is true, the code modifies the condition but does not return anything. React components must always return something (either JSX or null). If nothing is returned, the component won’t render anything, which is problematic.
3. "The Virtual DOM returned does not have a root element":
Problem: When props.condition is false, the component returns two adjacent <p> elements without a single root container. In JSX, you must wrap multiple elements in a single root element like a <div> or a React fragment (<>...</>). Without this, the code is invalid.
4. "Without declaring PropTypes, you cannot use props.condition and the code throws an error":
This is not correct. PropTypes are used to validate the types of props but are not required for the code to work. The absence of PropTypes won’t cause an error in this case.
Questions similairesPlus de questions sur React
26
Écrire l'équivalent non-JSX du code suivant :20
Écrire le code manquant pour afficher les enfants du composant UserProfile.13
Écrire un composant React en tant que fonction12
Appeler une fonction au premier rendu d'un composant React10
Enregistrer l'état utilisé pour afficher la page sélectionnée dans un composant React.