我从父组件获取道具并尝试渲染
从父组件,我传递标题
父组件:
class CoreCloudServices extends React.Component{
constructor(props){
super(props)
this.state = {
services:[]
}
}
loadData(){
var url = "https://api.myjson.com/bins/1ftfdx";
fetch(url)
.then(response => {
return response.json();
})
.then(d => {
this.setState({ services: d });
})
.catch(error => console.log(error))
}
componentDidMount() {
this.loadData();
}
render(){
<StatusFrame headings={this.state.services}/>
}
子组件:
class StatusFrame extends React.Component{
constructor(props){
super(props)
this.state = {
labelHeading : this.props.headings
}
}
componentWillReceiveProps(newProps)
{
this.setState({labelHeading: newProps.headings} , ()=>{
console.log(this.state.labelHeading);
});
}
render(){
return(
<div>
<div>
{
this.state.labelHeading.map(((head, index) => {
<div>child {head.title}</div>
})
)
}
</div>
</div>
)}}
this.state.labelHeading为null但我在componentwillreceiveprops()中设置状态
答案 0 :(得分:2)
你可以在不使用状态的情况下使用道具,你必须从你的父渲染方法返回,同样在地图回调中你也应该返回
class CoreCloudServices extends React.Component{
//...
render(){
return (<StatusFrame headings={this.state.services}/>)
}
}
class StatusFrame extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<div>
{
this.props.headings !== null ?
this.props.headings.map(( (head, index) =>
{
return <div>child {head.title}</div>
}))
:
null
}
</div>
</div>
)
}
}