我正在使用fetch()函数从api获取用户数据。在render函数中,我想使用... userdata传递道具,但是当我在return语句之前创建对象时,它给了我错误。错误是: TypeError:无法读取未定义的属性“ id”
错误是因为在加载应用程序时没有userData,仅在单击搜索按钮时才获取userData。
请让我知道如何创建对象并将其作为prop传递,而不是将对象的每个成员分别作为prop传递。即
import React from 'react';
import './App.css';
import SearchBar from "./components/search";
import Result from "./components/result";
class ContactSearch extends React.Component {
constructor() {
super();
this.state = {
// userData: {
// id: 0,
// name: "",
// username: ""
// },
userData : [],
userAddr : {},
searchDone: false,
errorMessage: ""
};
this.callUserData = this.callUserData.bind(this);
}
callUserData(user) {
const url = `<URL>`;
fetch(url)
.then(handleErrors)
.then(resp => resp.json())
.then(data => {
var { ...addr} = data[0].address;
this.setState({
userData: [...data],
userAddr: addr,
searchDone: true,
errorMessage: ""
});
})
.catch(error => {
// If an error is catch, it's sent to SearchBar as props
this.setState({ errorMessage: error.message });
});
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
}
render() {
const { searchDone, userData, userAddr, errorMessage } = this.state;
console.log('Inside render');
let **user** = {
id : userData[0].id,
name:userData[0].name,
email:userData[0].email,
address:userAddr
};
return (
<div className="ContactSearch">
<SearchBar
callBackFromParent={this.callUserData}
error={errorMessage}
/>
{searchDone && userData && (
<Result
{...**user**}
/>
)}
</div>
);
}
}
export default ContactSearch;
答案 0 :(得分:0)
您可以使用if语句检查所需的数据是否已经加载到状态中,以避免尝试在第一个渲染器上访问它:
const { searchDone, userData, userAddr, errorMessage } = this.state;
let user = null;
if (userData.length > 0) {
user = {
id : userData[0].id,
name:userData[0].name,
email:userData[0].email,
address:userAddr
};
}
做同一件事的更短方法:
const { searchDone, userData, userAddr, errorMessage } = this.state;
let user = searchDone && {
id : userData[0].id,
name:userData[0].name,
email:userData[0].email,
address:userAddr
};
答案 1 :(得分:0)
也许您需要
<Result user={searchDone && userData[0]} />
结果组件可能是这样
const Result=(props)=>
( props.user?<div>{props.user.id}</div>:'no result..^.^')
如果您的数据是
[{id:1},{id:2}]
从数据userData: [data]
应如下所示
userData: data,