![](/img/trans.png)
[英]How to update state if I have props coming from parent component in React Hooks
[英]React component not rendering props coming from parent
class CyInfo extends Component {
foo(){
console.log(this.props.id);
return getAttributes(this.props.id)
}
render() {
return ( <Info data = {this.foo()}> </Info>)
}
}
此父级接收“props.id”并将数据值传递给getAttributes()返回的子级。
export default class Info extends Component {
constructor(props){
super(props)
}
/*componentWillReceiveProps(nextProps){
console.log(nextProps);
*/
render() {
console.log(this.props.data);
return (
<div id="info">{this.props.data}</div>
)
}
}
在孩子上我可以在控制台和componentWillReceiveProps中看到道具值。但是数组不能渲染。 我尝试使用react-devtool。 在react-devtool道具似乎传递了孩子而不是渲染。 有趣的是,当我改变一些数组的元素数组时,react-devtool正在渲染。
我做错了什么。
编辑:[React-Devtool截图] [1]
我编辑了react-devtool截图。 看似道具,但组件只呈现初始值。 在屏幕截图控制台错误是favicon只是忽略这一点
EDIT2: 控制台打印道具数组
道具来自函数(getattributes),它调用异步方法,当这个道具传递给孩子时,不会渲染。 我直接在父子中调用async方法,并在componentWillReceiveProps中使用回调设置状态:
componentWillReceiveProps(nextProps){
self = this;
AsyncFunc(nextProps.id ,(error, result) => {
self.setState({data:result})
});
}
和渲染
return (<div id="info">
{Array.isArray(this.state.data) && this.state.data.map((data) => {
return <div key={data._id}>{data.class}{data.predicate}{data.yuklem}</div>
})}</div>
)
由于foo
是一个函数,你必须传递给子组件:
return ( <Info data = {() => this.foo()}> </Info>)
此外, data是一个数组 ,您必须使用.map()进行渲染,如下所示:
export default class Info extends Component {
constructor(props){
super(props)
}
/*componentWillReceiveProps(nextProps){
console.log(nextProps);
*/
render() {
console.log(this.props.data);
return (
<div id="info">{this.props.data.map(( element, index ) => {
console.log(element);
<span key={index}> {element}</span>})}
</div>
)
}
}
正如您所提到的, this.data.props
返回一个数组,并且为了在数组中呈现元素,您需要映射数组元素并在渲染之前检查data is an array or not
因为最初值可能不可用或不是数组
export default class Info extends Component {
constructor(props){
super(props)
}
/*componentWillReceiveProps(nextProps){
console.log(nextProps);
*/
render() {
console.log(this.props.data);
return (
<div id="info">
{this.props.data && Array.isArray(this.props.data) && this.props.data.map((data, index) => {
return <div key={index}>{data}</div>
})}</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.