[英]useState with value that may be null
I am new to React and have a question about useState
.我是 React 的新手,有一个关于
useState
的问题。 I have this code:我有这个代码:
const [value, setValue] = useState(props.selectedNote.content);
The problem is that selectedNote
is sometimes null
and sometimes not.问题是
selectedNote
有时是null
有时不是。 If it is null
then this throws an error.如果它为
null
则会引发错误。 How can I work around this?我该如何解决这个问题?
Optional chaining is fantastic: 可选链接很棒:
const [value, setValue] = useState(props.selectedNote?.content);
If you want a default value in the case that selectedNote (or content) is null/undefined then you can use nullish coalescing如果您想要在 selectedNote(或内容)为空/未定义的情况下的默认值,那么您可以使用空合并
const [value, setValue] = useState(props.selectedNote?.content ?? 'default');
你可以试试
const [value, setValue] = useState(props.selectedNote?props.selectedNote.content:null)
You can manage it with a ternary operator as suggested by @deepakgupta.您可以按照@deepakgupta 的建议使用三元运算符来管理它。 Another possibility, useful when you have a lot of props to check, is that of assign
defaultProps
to the component.当你有很多 props 需要检查时,另一种可能很有用,就是将
defaultProps
分配给组件。 This will avoid all a bunch of check inside component body and let the code more clean.这将避免组件主体内部的所有一堆检查,让代码更干净。
function myComponent(props) {
const [value, setValue] = useState(props.selectedNote.content);
}
myComponent.defaultProps = {
selectedNote : {
content : null
}
...
anotherProp : 'my default value'
}
It's depends from your application business logic.这取决于您的应用程序业务逻辑。
const Comp = (props) => {
const [value, setValue] = useState(props.selectedNote?.content);
return value ? < some your staff > : <SkeletonForNoValue />;
}
const Comp = (props) => {
const [value, setValue] = useState(props.selectedNote?.content || defaultNote);
const Comp = (props) => {
const [value, setValue] = useState(props.selectedNote?.content);
useEffect(
() => {
history.push({
pathname: '/path/to/go'
}
},
[props.selectedNote]
)
尝试这个:-
const [value, setValue] = useState(props.selectedNote && props.selectedNote.content);
试试这个: const [value, setValue] = useState(props.selectedNote?.content || defaultNote);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.