反应挂钩:TypeError:无法读取null的属性“ firstName”

时间:2019-08-28 08:15:46

标签: javascript reactjs ecmascript-6 react-hooks

我正在尝试在React挂钩中提取值,但是与此同时,当我控制台customer时遇到此错误TypeError: Cannot read property 'firstName' of null,我不知道我的代码中有什么问题。我是React Hook的新手,有人可以帮助我如何解决此问题。

谢谢

当我管理Customer时,我得到了这个结果

Result View

当我管理customer.firstName

它给我错误

代码

 const [customer, setCustomer] = useState(null);
  async function fetchMyAPI() {
    let response = await fetch(
      `/api/requirements/find?customerId=${item.customerId}`
    );
    response = await response.json();
    console.log(response);
    setCustomer(response);
  }

  useEffect(async () => {
    fetchMyAPI();
  }, []);

返回功能

{console.log(customer.firstName)}

2 个答案:

答案 0 :(得分:2)

该错误是有道理的,您正在使用Object notation来获得属于非对象的值。

只需将您的初始状态设置为空对象即可解决控制台错误:

 const [customer, setCustomer] = useState({});

总代码:

const Customer = () => {
 const [customer, setCustomer] = useState(null);
  async function fetchMyAPI() {
    let response = await fetch(
      `/api/requirements/find?customerId=${item.customerId}`
    );
    let data = await response.json();
    console.log(data);
    setCustomer(data);
  }

  useEffect(async () => {
    fetchMyAPI();
  }, []);

  return(
    <div>
       <h4>{customer.firstName}</h4>
       <h4>{customer.lastName}</h4>   
    </div>
  )
}

答案 1 :(得分:0)

您可以将初始状态设置为空白对象,如下所示...

const [customer, setCustomer] = useState({});


您可以按如下所示设置对象的默认结构...

const [customer, setCustomer] = useState({firstName: '', lastName: ''});