javascript - React Native for Web:我的组件在状态更新时不会重新渲染
问题描述
我是 React 新手,过去 2 天我一直在研究 React。我正在尝试从 API 获取数据。但是当数据更新时,状态不会更新,组件也不会重新渲染。但是刷新页面就可以完成这项工作。
这是我的组件的代码:
import { View, FlatList, Text, TouchableOpacity } from 'react-native'
class Products extends Component {
constructor(props){
super(props);
this.state={
dataSource: []
}
}
componentDidMount(){
fetch("http://localhost:8000/index.php")
.then(response => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson
})
})
.catch(error => console.log(error))
}
renderItem = (data) =>
<TouchableOpacity>
<Text>{data.item.product_name}</Text>
<Text>{data.item.product_description}</Text>
<Text>{data.item.product_model}</Text></TouchableOpacity>
return (
<View>
<FlatList
data={this.state.dataSource}
renderItem={item => this.renderItem(item)}
keyExtractor={item => item.id}
/>
</View>
)
}
export default Products
解决方案
return(...)
使用基于类的组件时必须使用render()
函数包装。
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
renderItem={item => this.renderItem(item)}
keyExtractor={item => item.id}
/>
</View>
);
}
推荐阅读
- eclipse - Eclipse 格式化程序只是缩进
- java - 使用 appium 运行我的测试脚本时出现 SecurtyException
- python - 如何从字典中的值中获取 key_name?
- r - 重新发布图书时关闭更新提示
- android - 如何在laravel 5.7中使用retrofit send to api从android创建护照令牌,还有比护照更好的选择来进行身份验证
- tensorflow - TensorBoard 上(正确的)ANN 偏差和权重是什么样的?
- javascript - React Native Firebase:从firebase读取数据时出错
- javascript - How can I set value to componentDidMount from another function in React?
- c - 从 C 中获取 *ABS* 符号的值
- codenameone - 代号一透支