如何处理初始空值 react.js

How to deal with initial null values react.js

我有意见。它的示例代码是

const [a, seta] = useState(null)
useEffect(() => {
        if(!a){

            geta(match.params.id);
        }
    })
return (
a.props
);

但它给出错误无法读取 属性 的空值

为什么会出错?

您的代码 returns a.props 在 useEffect 赋值 a 之前。实际上你是 returning 空的道具,因此错误。

"By default, effects run after every completed render" - React docs

如何修复

您可以有条件地 return 数据:return(a && a.props ? a.props : null)

举个上下文中的例子,这样的事情应该有效:

const [a, seta] = useState(null)
  useEffect(() => {
          if(!a){
              seta({greeting: 'Hello World'});
          }
      })
  return (
    a && a.greeting ? a.greeting : null
  )
}

以下代码 return 是一个错误,因为 auseEffect 开始并更新 a 的值之前在第一次渲染时为空。

import React, { useState, useEffect } from 'react';

const App = () => {

  const [a, seta] = useState(null)
  useEffect(() => {
    /*  ... do what you need to do */
  }, [])

  return (
    <div className="App">
      <h1>Your state:</h1>
      <h2>{a.props}</h2>
    </div>
  );
}

export default App;


相反,在 return 函数中添加类型保护以防止 null 值在 useEffect 触发之前:

import React, { useState, useEffect } from "react";

const App = () => {
  const [a, seta] = useState(null);
  useEffect(() => {
    /*  ... do what you need to do */
    setTimeout(() => seta({ props: 'test'}), 3000);
  }, []);

  return (
    <div className="App">
      <h1>Your state:</h1>
      {/* <h2>{a.props}</h2> // an erroneous return value */}
      <h2>{a !== null && a.props !== null ? a.props : "Loading ..."}</h2>
    </div>
  );
};

export default App;

工作代码沙箱:https://codesandbox.io/s/stack-66736637-nullinreturn-6or9f