Consider I got two ponents:
// Hello.js
import React from "react";
export default function Hello(props) {
const { name = "mike" } = props;
return <div>Hello {name}</div>;
}
// App.js
import React from "react";
import Hello from "./Hello";
export default function App() {
return (
<div>
<Hello name={null} />
</div>
);
}
// renders Hello
If I pass null
props to the Hello
ponent, The Hello
ponent will not use the default value, instead, it will just use null
as a value and render it.
The default value will only be used when i explicitly pass undefined
or not pass anything:
<Hello name={undefined} />
<Hello />
// renders Hello mike
So my question is How should i handle null props correctly? Should i handle it in parent ponent when pass it to child ponent like this:
// App.js
<Hello name={getName() || 'mike'} />
Or i should handle it in child ponent like this:
// Hello.js
return <div>Hello {name || "mike"}</div>;
Is there any "best practice" to help handle this?
Consider I got two ponents:
// Hello.js
import React from "react";
export default function Hello(props) {
const { name = "mike" } = props;
return <div>Hello {name}</div>;
}
// App.js
import React from "react";
import Hello from "./Hello";
export default function App() {
return (
<div>
<Hello name={null} />
</div>
);
}
// renders Hello
If I pass null
props to the Hello
ponent, The Hello
ponent will not use the default value, instead, it will just use null
as a value and render it.
The default value will only be used when i explicitly pass undefined
or not pass anything:
<Hello name={undefined} />
<Hello />
// renders Hello mike
So my question is How should i handle null props correctly? Should i handle it in parent ponent when pass it to child ponent like this:
// App.js
<Hello name={getName() || 'mike'} />
Or i should handle it in child ponent like this:
// Hello.js
return <div>Hello {name || "mike"}</div>;
Is there any "best practice" to help handle this?
Share Improve this question edited Nov 24, 2020 at 7:37 Sarun UK 6,7667 gold badges26 silver badges50 bronze badges asked Nov 24, 2020 at 6:54 LimboerLimboer 4146 silver badges33 bronze badges2 Answers
Reset to default 3You can use JS null coalescing operator to achieve in a below way:
props.name ?? 'Default value'
bad, cos somebody else will forget and yell WTF
// App.js
<Hello name={getName() || 'mike'} />
so so, but this is ugly, assign default value is more elegant
// Hello.js
return <div>Hello {name || "mike"}</div>;
better, why not just return string or undefined
function getName(){
...
return something || undefined
}
best, people wont always do so, how to make sure? TypeScript will check it when pile
interface Props {
name: string;
}
interface State {
xxx: xxx
}
class Hello extends React.Component<Props, State> {
choose as you like, cos best costs most
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745468941a4629043.html
评论列表(0条)