【问题标题】:How to load a list on page startup with user_id using useEffect如何使用 useEffect 在页面启动时使用 user_id 加载列表
【发布时间】: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


    【解决方案1】:

    这个组件有几个问题。

    • useEffect 必须接受不带参数的函数。类似于() =&gt; { /* effect*/ }。通过传递newuser_id,它掩盖了之前在代码中声明的变量。因此,将其从参数中移除,并将其传递到依赖数组中。对了,你为什么还要声明newuser_id而不是直接使用user_id
    • setKmListe 安排更新。 kmListe 不会立即更新。

    【讨论】:

    • 好的,当我删除 newuser_id/user_id 时,我收到了上面提到的警告,当我现在删除它时,它仍然没有进入 useEffect,newuser_id 的原因只是为了检查它是否进入 @罗德里戈阿马拉尔
    【解决方案2】:

    警告提到了钩子依赖项。不确定这是否能解决你所有的问题,但我觉得这是一个好的开始。

    依赖被定义为useEffect钩子的第二个参数。

    例子:

    useEffect(() => {
      const fetchUser = async () => {
        const response = await fetch(`http://something.com/users/%{userId}`);
        const user = await response.json();
        setUser(user);
      };
      if (userId) fetchUser();
    }, [userId])
    

    请注意,userIduseEffect 挂钩依赖项的一部分。

    一般规则是不要对依赖项撒谎。意味着如果某些内容在您的 useEffect 之外定义,但在内部使用,则它应该是依赖项的一部分。

    阅读更多here

    另外,kmListe 是一个钩子依赖项是一个等待发生的无限循环,因为您重新定义了钩子内部的状态。每次更改状态时,由于它是依赖项的一部分,因此效果会在每次渲染时再次运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 2020-04-30
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多