使用道具中的对象数组设置默认使用状态

Set default usestate with array of objects from props

我有一个奇怪的情况。我有以下不起作用的代码。

const [result, setResult] = useState(props.fileNamesStatus.map((file, i) => {
    return {
        key: file.fileStatus
    }
}));

奇怪的是,它有时有效,有时无效。我在 JSX 中使用它如下:

I get the error Cannot read property 'key' of undefined

<ul className="in">
     {props.fileNamesStatus.map((file, i) => {
           console.log(result[i].key)     /// Cannot read property 'key' of undefined
    
     })}
</ul>

您需要添加另一个 useEffect 挂钩:

useEffect(() => {
  if (props.fileNamesStatus && props.fileNamesStatus.length) {
    setResult(props.fileNamesStatus.map((file, i) => {
      return {
        key: file.fileStatus
      }
    }))
  }
}, [props.fileNamesStatus])

但即使进行了此更改,您的渲染道具和状态也有可能不同步,因此您应该添加额外的检查 console.log(result[i] ? result[i].key : 'out of sync')