reactjs - 在 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 始终为空。
也许有人可以帮助我?
非常感谢
解决方案
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 beforerender()
, or - Put it in the
render()
function before thereturn
statement.
推荐阅读
- javascript - JS 在 iOS 设备上无法正常工作 - 仅有时
- php - 将集合中的值相乘
- java - 我怎样才能在java中更快地做到这一点?复制长字符串的字符
- c++ - 三向比较取代了除 == 之外的所有其他比较运算符?
- reactjs - 未捕获的 DOMException:无法在“IDBObjectStore”上执行“删除”:事务未处于活动状态
- macos - 为节点 v12 安装 babel cli 时出现奇怪的错误日志
- java - 使用 OR-Tools 表达多变量约束
- pytorch - 强化学习中是否有任何方法可以选择多个同时动作?
- c# - 我想创建一个 Excel 电子表格,其中每个工作表都是一个列表。关于如何做到这一点的任何建议。我需要列出清单吗?
- javascript - React,JS - 使用 refs 的不同方式的功能差异