[英]Array with three elements but length 0
我在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>
);
}
首先,它將呈現文本,並將this.props.data打印為空。 然后在數據中打印三個元素,但長度為0,並且不重新渲染
---編輯---這是生成數據並將其傳遞給無法正常工作的組件的父組件的代碼:
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>
);
}
}
傳遞新道具時,狀態可能不會刷新。嘗試使用componentDidUpdate
。
componentDidUpdate(prevProps){
if(prevProps.data !== this.props.data) {
this.setState({data: prevProps.data})
}
}
如果this.props.data
更新,這將強制狀態更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.