【发布时间】:2021-08-31 10:53:36
【问题描述】:
我正在尝试更新具有父状态道具的子组件。在将 setState() 更改为我的知识的父级状态时,chlid 应该重新渲染。但是当孩子在数组中时,不会发生重新渲染。我该如何解决?
提前致谢。
我的孩子班:
class Child extends Component {
render() {
return(
<Text>{this.props.state.isActive.toString()}</Text>
)
}
}
我的父类:
class Parent extends Component {
state = {
isActive: false
}
children = []
constructor(props) {
super(props)
this.createChildren()
this.changeState()
}
changeState() {
this.change = setInterval(() => {
if(this.state.isActive){
this.setState({isActive: false})
} else {
this.setState({isActive: true})
}
}, 1000)
}
componentWillUnmount() {
clearInterval(this.change)
}
createChildren() {
for(let i=0; i<5; i++) {
this.children.push(<Child key={i} state={this.state}/>)
}
}
render() {
return(
<View>
{this.children}
</View>
)
}
}
我的应用功能:
export default function App() {
return (
<View style={style.conteiner}>
<Parent/>
</View>
);
}
【问题讨论】:
-
根据您的父组件-> 子组件设置,我认为这篇 SO 帖子可能会对您有所帮助:stackoverflow.com/a/41233828/1188197
标签: reactjs react-native