首页 > 解决方案 > 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

标签: javascriptreactjsreact-native

解决方案


return(...)使用基于类的组件时必须使用render()函数包装。

    render() {
        return (
            <View>
                <FlatList
                    data={this.state.dataSource}
                    renderItem={item => this.renderItem(item)}
                    keyExtractor={item => item.id}
                />
            </View>
        );
    }

推荐阅读