首页 > 解决方案 > 在 componentDidMount 之后反应不渲染组件

问题描述

我有一个组件,它在 componentDidMount 之后没有重新渲染。

渲染方法看起来像这样:

render() {
            {
                console.log("----------RENDERING-----------------------------")
            }
            return (
            <ImageBackground
                source={require('../assets/images/bg.png')}
                style={styles.bg}
            >
                <View style={styles.containerHome}>
                    <View style={styles.top}>
                        <City/>
                        <Text>myapp</Text>
                        {/*<Filters />*/}
                    </View>

                    <CardStack
                        loop={true}
                        verticalSwipe={false}
                        renderNoMoreCards={() => null}
                        ref={swiper => (this.swiper = swiper)}
                    >
                        {this.state.data.map((item, index) => (
                            <Card key={index}>
                                <CardItem
                                    text={item.name}
                                    detail={item.detail}
                                    imageurl={item.imageurl}
                                    matches="0"
                                    actions
                                    onPressLeft={() => this.swiper.swipeLeft()}
                                    onPressRight={() => this.swiper.swipeRight()}
                                />
                            </Card>
                        ))}
                    </CardStack>
                </View>
            </ImageBackground>
        );
    }

...简单地渲染一个卡片组。

这里相关的是这一行:

this.state.data.map((item, index) => (

如果我从文件(演示)中设置数据静态,它正在工作!

表示如果这条线看起来像这样

Demo.map((item, index) => (

一切都没事!

但是当我在componentDidMount中设置数据时,它不起作用!我真的不知道 react-native 在这里做什么:

componentDidMount() {
        this.setState({
            isLoaded: true,
            data: Demo
        });

我将 state.data 设置为完全相同的演示值,但反应不是重新渲染。

似乎 this.state.data 始终为空。

也许有人可以帮助我?

非常感谢

标签: reactjsreact-nativereact-native-android

解决方案


ComponentDidMount() executes after the render() function, so you had better do this before rendering and outside of ComponentDidMount():

this.setState({
    isLoaded: true,
    data: Demo
});

So initially, before render(), you have to set some value of data.

Try with three possible answers:

  • Default value {data:Demo}, or
  • Implement this.state in a function which can be executed before render(), or
  • Put it in the render() function before the return statement.

推荐阅读