javascript - react Hook : TypeError: Cannot read property 'firstName' of null

标签 javascript reactjs ecmascript-6 react-hooks

我正在尝试在 React Hook 中提取值,但与此同时,当我安慰 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)}

最佳答案

这个错误是有道理的,您正在使用 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>
  )
}

关于javascript - react Hook : TypeError: Cannot read property 'firstName' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57687849/

相关文章:

javascript - 多次评估或加载远程脚本

javascript - jQuery: hide() 有效 click() 无效

javascript - 如何从当前状态向前或向后旋转元素

javascript - React 模块和包装 Google Recaptcha

javascript - this.setState 不起作用(我的状态是一个数字)

javascript - ES6 Symbol 能保证 100% 唯一标识符吗?

javascript - ECMA 6、React Native 和 Redux : what does this syntactic sugar mean?

javascript - 语法 `foo(a)(b)` 有什么用处?

reactjs - react-select typescript 问题 - 通用类型 'ValueType' 需要 2 个类型参数。ts(2314)

javascript - Es6 使用扩展合并两个对象不起作用