我在这里有这个反应代码,称为api。
第一个console.log调用返回了数据,但是第二个console.log未定义。
我在哪里错了?感谢您指出我的错误,并非常感谢
export default class ProfileDetail extends Component {
state = {
prodetail:'',
}
async componentDidMount(){
const id = this.props.match.params.id
const searchurl = `https://www.demo.com/api/personinfo/persondetail?id=${id}`;
const res = await axios.get(searchurl);
this.setState({prodetail:res.data});
}
render() {
const{ prodetail
} = this.state
console.log(prodetail)
console.log(prodetail.firstname)
假设您引用的是第一个渲染,这是预期的。
On the first render,
prodetail
is just an empty string. Then onlycomponentDidMount
is invoked. On top of that, yourcomponentDidMount
is an async function, which will only setprodetail
untilaxios.get
is returned.Instead, you might want to defer rendering data needed with
prodetail
until your request is resolved. For example