[英]why react props are passed undefined to the child component?
我从db获取了一些数据,当我在控制台上记录它们时效果很好。 并且当我把所传递的道具打开时,它们可以正常显示在屏幕上。
import axios from 'axios'
import { URL } from '../../../../config'
import Header from './header'
class NewArticle extends Component {
state = {
article: [],
team: []
}
componentWillMount() {
axios.get(`${ URL }/articles?id=${ this.props.match.params.id }`)
.then( res => {
let article = res.data[ 0 ]
console.log( res.data[ 0 ] )
//{
// author: "John Secada",
// date: "10/12/2018",
// }
axios.get( `${ URL }/teams?id=${ article.team }` )
.then( res => {
this.setState({
article,
team: res.data[0]
})
console.log( res.data[0] )
// {
// id: 3,
// logo: "nets.png",
// name: "Nets",
// poll: "false",
// stats: {wins: 23, defeats: 12}
// }
} )
} )
}
render(){
let article = this.state.article
let team = this.state.team
return(
<div>
<Header
teamData={ team }
date={ article.date }
author={ article.author }
/>
{ JSON.stringify(article,team) }
</div>
)
}
}
export default NewArticle
接收道具的Header组件:
import React from 'react'
const Header = props => {
return (
<div>
{ console.log( props) }
{/* {teamData: Array(0), date: undefined, author: undefined} */}
</div>
)
}
export default Header
那么,当我将它们作为道具传递给Header组件时,为什么它们是未定义的?
因为您有异步请求,并且在挂载Header时您还没有这些数据。
尝试这个:
render(){
const article = this.state.article
const team = this.state.team
if(!article && !article.date && !article.author) {
return null;
}
if(!team) {
return null;
}
return(
<div>
<Header
teamData={ team }
date={ article.date }
author={ article.author }
/>
{ JSON.stringify(article,team) }
</div>
)
}
在componentWillMount中,您使用的是axios ,它返回一个promise并且是异步的。 问题是您在从API获取数据之前呈现<Header/>
。 要避免这种情况,您可以像这样更新render
功能。
function render() {
let article = this.state.article;
let team = this.state.team;
return (
<div>
{team.length ? (
<Header teamData={team} date={article.date} author={article.author} />
) : (
'Loading Data...'
)}
{JSON.stringify(article, team)}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.