具有三个元素但长度为0的数组

时间:2019-05-13 13:42:17

标签: javascript reactjs react-native

我在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>
        );
    }
}

1 个答案:

答案 0 :(得分:-1)

传入新道具时状态可能不会刷新。尝试使用componentDidUpdate

componentDidUpdate(prevProps){
    if(prevProps.data !== this.props.data) {
        this.setState({data: prevProps.data})
    }
}

如果this.props.data更新,这将强制状态更新。

相关问题