简体   繁体   English

useState 的值可能为 null

[英]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.这取决于您的应用程序业务逻辑。

  1. Conditional Rendering条件渲染
const Comp = (props) => {
   const [value, setValue] = useState(props.selectedNote?.content);

   return value ? < some your staff > : <SkeletonForNoValue />;
}
  1. You may define default value您可以定义默认值
const Comp = (props) => {
   const [value, setValue] = useState(props.selectedNote?.content || defaultNote);

  1. Push to another route推到另一条路线
const Comp = (props) => {
   const [value, setValue] = useState(props.selectedNote?.content);

   useEffect(
     () => {
        history.push({
          pathname: '/path/to/go'
        }
     },
     [props.selectedNote]
   )
  1. Any other logic implementation...任何其他逻辑实现...

尝试这个:-

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM