【发布时间】:2020-09-06 16:26:31
【问题描述】:
我一直在尝试从从父页面获得的 user_id 加载页面上的列表,但我不断收到 React Hook useEffect 缺少依赖项:'newuser_id'。要么包含它,要么删除依赖数组 react-hooks/exhaustive-deps 警告,然后出现错误提示 Uncaught TypeError: Cannot read property 'length' of undefined 现在它甚至不读取不再使用 useEffect..
这是我的文件:
import React, {useEffect, useState} from 'react';
import { authenticationService } from '../../services/authentication.service';
export default function Kilometer({user_id}) {
const [kmListe, setKmListe] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(false);
console.log('root ' + user_id);
useEffect(() => {
console.log('useEffect' + user_id)
setIsLoading(true)
if(!user_id){
setKmListe('')
console.log('!user_id ' + kmListe)
}else{
const getData = async () => {
await authenticationService.kmliste(user_id)
.then(
km => {
console.log('test 1 '+JSON.stringify(km))
setKmListe(JSON.stringify(km))
setIsLoading(false)
}
).catch(err => {
console.log('catch ' + err)
setError(true)
setIsLoading(false)
})};
getData()
}
}, [kmListe])
const liste =
setIsLoading(true)
if(kmListe === ''){
console.log('blank '+kmListe)
return ['No list','add km to make a list'];
}else{
kmListe.map(listen =>{
console.log('map ' + listen)
return(
<div key={listen.id}>
<div>
<h1>{listen.km_start} {listen.km_slut}</h1>
<h2>{listen.start_by} {listen.slut_by}</h2>
</div>
</div>
)
})}
console.log('return '+liste)
return error ?
<h1>{error}</h1> :
isLoading ?
<h1>LOADING.......</h1> :
liste.length ? <h1>{error}</h1> : (
<div>
{liste}
</div>
);
}
我已将 console.logs 保存在代码中,因此您可以从控制台上的输出中看到正在运行的内容
根 2
返回未定义
根 2
返回未定义
编辑 现在无论我做什么 useEffect 根本不会触发,我卡住了,我不知道如何克服它。 我试图删除 newuser_id 并尝试创建一个新页面但结果相同..
【问题讨论】:
标签: reactjs use-effect use-state