简体   繁体   English

反应 UseEffect 和 UseState object 未定义错误

[英]React UseEffect and UseState object undefined error

In my ClientData.js在我的 ClientData.js

I am using useEffect to call an API(which is working), then using useState to set the API response.data to a variable(which is working).我正在使用 useEffect 调用 API(正在工作),然后使用 useState 将 API response.data 设置为变量(正在工作)。

The response.data is an array of objects which I then set equal to a local variable. response.data 是一个对象数组,然后我将其设置为等于局部变量。 But when I attempt to access the object parameter I get a object undefined error.但是当我尝试访问 object 参数时,我得到一个 object 未定义错误。

I think the problem might be is that the object is undefined due to it waiting for the API response.我认为问题可能是 object 未定义,因为它正在等待 API 响应。

This is what the object from the API looks like:这是 API 中的 object 的样子:

objTest={
  ClientDatabase: "21",
  ClientID: "21",
  ClientName: "21",
  ClientServer: "21",
  Country: "US - 21",
  DatabaseVersion: "21",
  Namespace: "21",
};

function SimpleSelect() {
    const classes = useStyles();
    

    const [objTest, setobjTest] = useState([]);

    const clientAPI =  useCallback( async() => {
       
      //returns an array of objects
           await axios({
            method:'get',
             url,
            auth: {
                username: user,
                password: pass
            }
        })
        .then(function(response) {
  
         
            setobjTest(  response.data)
    
      
  
      
        })
        .catch(function (error){
            console.log(error);
        });

    })
    useEffect( () => {
        clientAPI();
        

        
    }, [])

When I attempt to access the object it works using console.log((objTest[0]));当我尝试访问 object 时,它使用console.log((objTest[0]));

but when I attempt to access the objects parameter like this: console.log((objTest[0].ClientDatabase));但是当我尝试像这样访问 objects 参数时: console.log((objTest[0].ClientDatabase));

it returns它返回

TypeError: Cannot read property 'ClientDatabase' of undefined TypeError:无法读取未定义的属性“ClientDatabase”

This is the console log of response.data enter image description here这是 response.data 的控制台日志 在此处输入图像描述

The response.data is an array. response.data 是一个数组。

You put the initial state as an empty array.您将初始 state 作为空数组。 That's why you can't access it's first element.这就是为什么你不能访问它的第一个元素。 you can either set a non empty array as the initial state like this您可以像这样将非空数组设置为初始 state

const obj=[{
  ClientDatabase: "21",
  ClientID: "21",
  ClientName: "21",
  ClientServer: "21",
  Country: "US - 21",
  DatabaseVersion: "21",
  Namespace: "21",
}];

const [objTest, setobjTest] = useState(obj);

or you can check if the array is not empty或者您可以检查数组是否为空

objTest.length && console.log(objTest[0].ClientDatabase)

The api call will take some time fetch the data. api 调用将需要一些时间来获取数据。 The initial state is what gives you the error最初的 state 是什么给你的错误

<Select labelId="demo-simple-select-label" id="demo-simple-select" value={age} onChange={handleChange} > {objTest.length && objTest.map(myList => { return( <MenuItem key = {myList.ClientDatabase} value = {myList} > {myList.ClientName} + {myList.Site} </MenuItem> ) })} </Select>

Try this out试试这个

Edit:编辑:

useEffect( () => console.log(objTest[0].ClientDatabase), [objTest])

The issue is with when you're logging the data.问题在于您何时记录数据。 You're logging it a bit early.你记录的有点早。

So to check the modified state you can use an additional useEffect hook.因此,要检查修改后的 state,您可以使用额外的useEffect挂钩。

useEffect(() => {
  if(objTest.length > 0) {
    console.log(objTest[0].ClientDatabase)
  }
}, [objTest])

And when you want to use this in the JSX you can check if it's populated:当你想在 JSX 中使用它时,你可以检查它是否被填充:

{
    clientArrTwo.length > 0 ? <Select labelId="demo-simple-select-label"
        id="demo-simple-select"
        value={age}
        onChange={handleChange} >
        {clientArrTwo.map(myList => {
            return (<MenuItem key={myList.ClientDatabase} value={myList} > {myList.ClientName} + {myList.Site} </MenuItem>)

        })}
    </Select> : null
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM