我正在尝试在 React Hook 中提取值,但与此同时,当我安慰 customer
时,我收到此错误 TypeError: Cannot read property 'firstName' of null
我不知道不知道我的代码有什么问题。我是 React Hook 的新手,有人可以帮我解决这个问题吗?
谢谢
当我安慰 Customer 时,我得到了这个结果
当我安慰 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/