[英]Array with three elements but length 0
I have a component in my React Native project if you pass it data in props it renders it but if you don't it renders some text. 我在React Native项目中有一个组件,如果您在props中传递数据,它会渲染它,但是如果没有,它会渲染一些文本。
constructor(props) {
super(props);
this.state = {
dropDownAnimation: new Animated.Value(0),
dropDownElements: false,
data: props.data
}
}
getSnapshotBeforeUpdate(prevProps, prevState) {
if(prevProps.open != this.props.open || this.props.data != prevProps.data) {
return true;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot == true) {
console.log('componentdidupdate', this.props)
this.runAnimation();
this.setState({data: this.props.data})
}
}
render() {
console.log('data', this.state.data[0], this.state.data[0] == undefined)
return (
<View>
{this.state.data.length > 0 ? this.renderDropDownElements() : this.props.noElementComponent}
</View>
);
}
At the start it renders the text and it prints this.props.data as empty. 首先,它将呈现文本,并将this.props.data打印为空。 Then it prints three element in data but length 0 and it doesn't re-renders 然后在数据中打印三个元素,但长度为0,并且不重新渲染
--- EDIT --- this is the code of the parent component that produces data and passes it to the component which is not working properly: ---编辑---这是生成数据并将其传递给无法正常工作的组件的父组件的代码:
class Archive extends Component {
constructor() {
super();
this.state = {
data: [],
dropDownOpen: false,
}
this.getData();
}
getData = async () => {
var data = await returnImportantTasks(() => {})
this.setState({data: data})
}
render() {
return (
<View style={{flex: 1}}>
<View style={{ flex: 1, height: height, widht: width, alignItems: 'center', justifyContent: 'center' }}>
<Text>Compiti Importanti</Text>
<TouchableOpacity onPress={() => this.setState((prevState) => ({dropDownOpen: !prevState.dropDownOpen}))}><Text>Open</Text></TouchableOpacity>
<DropDownPicker
child={<SubjectCard/>}
data={this.state.data}
open={this.state.dropDownOpen}
noElementComponent={<Text>Non ci sono compiti importanti</Text>}
/>
</View>
<TouchableOpacity
style={styles.menuBtn}
onPress={() => {this.props.navigation.openDrawer()}}
>
<BaseCard style={styles.circle}>
<MenuIcon />
</BaseCard>
</TouchableOpacity>
</View>
);
}
}
The state might not be refreshing when the new props are being passed in. Try using componentDidUpdate
. 传递新道具时,状态可能不会刷新。尝试使用componentDidUpdate
。
componentDidUpdate(prevProps){
if(prevProps.data !== this.props.data) {
this.setState({data: prevProps.data})
}
}
This will force a state update if this.props.data
updates. 如果this.props.data
更新,这将强制状态更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.