1

我要做的是将新数据传递给 API 并将其显示在 FlatList 中。我所有的 CRUD 方法都通过了,但我的 FlatList 不会显示更改,直到我刷新我的“App.js”。我的“App.js”(如下所示)中的代码包含“delete”方法,该方法正在工作,我的 FlatList 会立即更新它,我猜是因为状态是本地的,FlatList 可以找到它。但是当我使用“PUT”和“POST”方法时,在其他组件中声明它不会对它做出反应。

在 react-native 以及在其中导航方面,我是一个完全的菜鸟。关于如何解决这个难题的任何提示?

class Fetch extends React.Component {
    static navigationOptions = {
        
        title: 'Blomster Boden',
    };
  
    constructor(props) {
        super(props);
        this.state = { isLoading: true }
     
        this.forceUpdate();

        
      
    }
    actionOnRow(item) {
        this.props.navigation.navigate('Details', { item });
        this.state
    }
    editOnRow(item) {
        this.props.navigation.navigate('Edit', { item });
    this.state
    }
    suckulenter(item) {
        this.props.navigation.navigate('Info', { item });
        this.state
    }


    componentDidMount() {
        this.getData()
    }
    
    getData = () => {
         fetch('http://192.168.10.135:3000/blommor/')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    isLoading: false,
                    dataSource: responseJson
                },
                );
            })
            .catch((error) => {
                console.error(error);
            });
    }
    

    delete(_id) {
        fetch('http://192.168.10.135:3000/blommor/' + _id,
            {
                method: "DELETE",
 
            }).then((result) => {
                result.json().then(() => {
                    alert("Blomman har tagits bort!")
                    this.getData()
                })
            })
            .catch((error) => {
                console.error(error);
            });
    }


    render() {
        if (this.state.isLoading) {
            return (
                <View style={styles.ActivityIndicator}>
                    <ActivityIndicator />
                </View>
            )
            
        }
        
        return (
            <View style={styles.container } >   
                <View style={styles.body}>
                    <Text h1 style={styles.h1}>Välkommen till blomsterboden</Text>
                   

                    <Card style={styles.card}>
                     
                        <Title style={styles.cardTitle}>Lista av våra blommor</Title>

         
                            


                         <FlatList  data={this.state.dataSource}

                        extraData={this.state}

                        renderItem={({ item }) =>

                            <TouchableWithoutFeedback onPress={() =>       
                                this.actionOnRow(item)}>
                                <Text style={styles.listTextStyle} numberOfLines={1} ellipsizeMode='middle'>
                                    <Text style={styles.Namn} >  {item.Namn}  </Text> 
                                    <IconButton
                                        icon="arrow-right"
                                        size={15}
                                    />

                                    <IconButton 
                                        icon="pencil"
                                        color={Colors.green400}
                                        size={20}
                                        title="Edit"
                                        onPress={() => this.editOnRow(item)}
                                    />

                                    <IconButton
                                        icon="delete"
                                        size={20}
                                        title="Ta bort"
                                        onPress={() => this.delete(item._id)}
                                    />

                                </Text>
                                
                            </TouchableWithoutFeedback>                         

                        }

                        keyExtractor={item => item._id.toString()}
                            /> 

                    </Card>
4

2 回答 2

0

发生这种情况是因为您的数据库不是实时数据库!因此,当您在屏幕之间导航时,您将希望使用事件侦听器来刷新列表,每次您添加帖子并返回列表时,导航侦听器将被触发并刷新您的列表,因此您的代码更新如下:

    class Fetch extends React.Component {
        static navigationOptions = {
            
            title: 'Blomster Boden',
        };
      
        constructor(props) {
            super(props);
            this.state = { isLoading: true }
         
            this.forceUpdate();
    
            
          
        }
        actionOnRow(item) {
            this.props.navigation.navigate('Details', { item });
            this.state
        }
        editOnRow(item) {
            this.props.navigation.navigate('Edit', { item });
        this.state
        }
        suckulenter(item) {
            this.props.navigation.navigate('Info', { item });
            this.state
        }


  //An event listener that will trigger when screen is focused
  componentDidMount() {
    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      this.getData()
    });
  }

  //Clean up the event listener
  componentWillUnmount() {
    this._unsubscribe();
  }

        getData = () => {
             fetch('http://192.168.10.135:3000/blommor/')
                .then((response) => response.json())
                .then((responseJson) => {
                    this.setState({
                        isLoading: false,
                        dataSource: responseJson
                    },
                    );
                })
                .catch((error) => {
                    console.error(error);
                });
        }
        
    
        delete(_id) {
            fetch('http://192.168.10.135:3000/blommor/' + _id,
                {
                    method: "DELETE",
     
                }).then((result) => {
                    result.json().then(() => {
                        alert("Blomman har tagits bort!")
                        this.getData()
                    })
                })
                .catch((error) => {
                    console.error(error);
                });
        }
    
    
        render() {
            if (this.state.isLoading) {
                return (
                    <View style={styles.ActivityIndicator}>
                        <ActivityIndicator />
                    </View>
                )
                
            }
            
            return (
                <View style={styles.container } >   
                    <View style={styles.body}>
                        <Text h1 style={styles.h1}>Välkommen till blomsterboden</Text>
                       
    
                        <Card style={styles.card}>
                         
                            <Title style={styles.cardTitle}>Lista av våra blommor</Title>
    
             
                                
    
    
                             <FlatList  data={this.state.dataSource}
    
                            extraData={this.state}
    
                            renderItem={({ item }) =>
    
                                <TouchableWithoutFeedback onPress={() =>       
                                    this.actionOnRow(item)}>
                                    <Text style={styles.listTextStyle} numberOfLines={1} ellipsizeMode='middle'>
                                        <Text style={styles.Namn} >  {item.Namn}  </Text> 
                                        <IconButton
                                            icon="arrow-right"
                                            size={15}
                                        />
    
                                        <IconButton 
                                            icon="pencil"
                                            color={Colors.green400}
                                            size={20}
                                            title="Edit"
                                            onPress={() => this.editOnRow(item)}
                                        />
    
                                        <IconButton
                                            icon="delete"
                                            size={20}
                                            title="Ta bort"
                                            onPress={() => this.delete(item._id)}
                                        />
    
                                    </Text>
                                    
                                </TouchableWithoutFeedback>                         
    
                            }
    
                            keyExtractor={item => item._id.toString()}
                                /> 
    
                        </Card>
于 2021-03-25T13:56:25.550 回答
0

嗯,有两种方法可以听到变化。如果它们在同一棵树中,您可以将一个函数从您的组件传递给其他组件。然后可以在它们各自的“PUT”或“POST”操作完成后将此函数作为回调函数调用。然后,函数本身将以与“DELETE”方法相同的方式设置状态。

class ParentComponent extends React.Component {
    // ...
    onStateChange(newState) {
        this.setState(newState);
    }

    render() {
        return <ChildComponent onParentStateChange={this.onStateChange} />
    }
    // ...
}

class ChildComponent extends React.Component {
    // ...
    onStateChange() {
        this.props.onParentStateChange({
            key: value
        });
    }
    // ...
}

如果它们不在同一棵树中,或者您不喜欢四处传递回调,则可以使用reducers选择更全局的解决方案。

于 2021-03-25T16:01:43.867 回答