简体   繁体   中英

FlatList not updating after CRUD in react-native

What I'm trying to do is to pass new data to a API and display it in a FlatList. All my CRUD-methods are passing, but my FlatList wont display the changes until I refresh my "App.js". The code in my "App.js" (as shown below) contains the "delete" method, which is working and my FlatList updates it right away, I guess it is since the state is local and the FlatList can find it. But when I use "PUT" and "POST" methods, that is declared in other components it doesn't react to it.

I'm a complete noob in react-native and when it comes to navigation within it. Any tips on how to solve this puzzle?

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>

Well that happen because your database is not realtime database, so when you navigate between screens you will want to use an event listener to refresh your list, every time you go and add post and get back to list the navigation listener will be triggered and will refresh your list: so here is your code updated:

    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>

Well, there are two ways to listen to changes. You either pass a function from your component to the other components if they are in the same tree. This function can then be called as a callback function after their respective "PUT" or "POST" action is complete. The function itself will then set the state the same way as in your "DELETE" method.

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
        });
    }
    // ...
}

If they are not in the same tree or you don't like passing callbacks around, you may opt for a more global solution by using reducers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM