Reactjs 无法使用componentWillReceiveProps呈现状态
我从父组件获取道具并尝试渲染 从父组件,我传递标题 父组件:Reactjs 无法使用componentWillReceiveProps呈现状态,reactjs,Reactjs,我从父组件获取道具并尝试渲染 从父组件,我传递标题 父组件: class CoreCloudServices extends React.Component{ constructor(props){ super(props) this.state = { services:[] } } loadData(){ var url = "https://api.myjson.com/bins/1ftfdx"; fetch(url)
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}/>
}
类CoreCloudServices扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
服务:[]
}
}
loadData(){
变量url=”https://api.myjson.com/bins/1ftfdx";
获取(url)
。然后(响应=>{
返回response.json();
})
.然后(d=>{
this.setState({services:d});
})
.catch(错误=>console.log(错误))
}
componentDidMount(){
这是loadData();
}
render(){
}
子组件:
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>
)}}
class StatusFrame扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
标签标题:this.props.headers
}
}
组件将接收道具(新道具)
{
this.setState({labelHeading:newProps.headings},()=>{
console.log(this.state.labelHeading);
});
}
render(){
返回(
{
this.state.labelHeading.map(((head,index)=>{
子{head.title}
})
)
}
)}}
this.state.labelHeading为null,但我正在componentwillreceiveprops()中设置状态。您可以只使用这些道具而不使用状态,并且必须从父渲染方法返回,也应该在映射回调中返回
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>
)
}
}
类CoreCloudServices扩展了React.Component{
//...
render(){
返回()
}
}
类StatusFrame扩展了React.Component{
建造师(道具){
超级(道具)
}
render(){
返回(
{
this.props.headers!==null?
this.props.headings.map((head,index)=>
{
返回子项{head.title}
}))
:
无效的
}
)
}
}
一切看起来都很好,为什么不直接使用this.props.headers而不使用state@Ali我正在从父组件更新道具。尝试更新componentWillReceiveProps中的状态,但无法更新render@Bhawna检查我的答案,它会有帮助you@Alithis.props.headers第一次为空。请检查此注释:我是从父组件更新道具。并且尝试更新componentWillReceiveProps中的状态,但无法在道具更改时渲染渲染。渲染方法将触发。初始值为null。让我与您共享父组件。检查我的编辑道具。在父组件中标题为nullahhh您忘记从re返回方法,签出编辑