从节点 REST API 获取数据并填充其他控件



React登录 Web 应用程序后,我将向用户显示配置文件详细信息,并且我正在从 NODE REST API 获取配置文件详细信息。我不知道该怎么做。我认为问题出在渲染部分,因为如果我不使用渲染部分,那么它就会向我显示一些数据。

export class AccountDetails extends Component {
constructor (props) {
super(props)
this.state = {
userDetail:null
}
this.callAPI()
}

async callAPI() {
await fetch("http://localhost:5000/customers?email="+JSON.parse(localStorage.getItem('email'))
.then(res=>res.json())
.then(res=>this.setState({userDetail:res}));
console.log(this.state.userDetail);
}

这是我的渲染部分

<tr>
<td className="text-left">First Name : </td>
<td className="text-left">{this.userDetail.firstName}</td>
</tr>

我在console.log中得到空

如果我不使用{this.userDetail.firstName}那么我就会得到

0:
email: "manu@gmail.com"
firstName: "Manpreet"
lastName: "Narang"
occupants: 2
phone: 12345
__proto__: Object
length: 1
__proto__: Array(0)

由于您使用的是类,因此您需要像这样componentDidMount进行获取:

constructor (props) {
super(props)
this.state = {
userDetail: null,
isLoaded: false // Notice this new property and check the render method below
}
}
componentDidMount() {
fetch("http://localhost:5000/customers?email="+JSON.parse(localStorage.getItem('email'))
.then(res => res.json())
.then(res => this.setState({ userDetail: res, isLoaded: true }));
}

只有这样,setState才能工作并重新渲染组件。

然后,在render方法中:

render() {
if(!isLoaded) return <p>Loading...</p>
return (
<tr>
<td className="text-left">First Name : </td>
<td className="text-left">{this.userDetail.firstName}</td>
</tr>
)
}

参考: https://reactjs.org/docs/react-component.html#componentdidmount

最新更新