jon*_*nny 1 javascript ecmascript-6 reactjs react-hooks
我试图在 React hooks 中提取价值,但与此同时,当我控制台时,customer我收到此错误TypeError: Cannot read property 'firstName' of null,我不知道我的代码中有什么问题。我是 React Hook 的新手,有人可以帮我解决这个问题吗?
谢谢
当我安慰客户时,我得到这个结果
当我安慰 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();
}, []);
Run Code Online (Sandbox Code Playgroud)
在返回函数中
{console.log(customer.firstName)}
Run Code Online (Sandbox Code Playgroud)
该错误是有道理的,您正在使用它Object notation来获取属于非对象的值。
只需将初始状态设置为空对象即可解决控制台错误:
const [customer, setCustomer] = useState({});
Run Code Online (Sandbox Code Playgroud)
整体代码:
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>
)
}
Run Code Online (Sandbox Code Playgroud)