简体   繁体   中英

Edit an array with useState React Native

I am trying to update an array of movies when somebody click on "Load films" after he has entered a movie title, but using useState and doing setFilms(films => [...films, data.results]); (updating the array and adding new movies to the existing empty one) do not work. What should I do? Here is my code:

function HomeScreen({ navigation }) {

        const [films, setFilms] = useState([]);
        let searchedText = "";
        let page = 0;
        let totalPages = 0;

        const searchInputChanged = text => {
            searchedText = text
        }

        const loadFilms = () => {
            if(searchedText.length > 0)
            {

                getFilmsFromApiWithSearchedText(searchedText, page+1).then(data => {
                    page = data.page
                    totalPages = data.total_pages

                    setFilms(films => [...films, data.results]);
                    console.log(films)

                })

            }
        }

        return (
        <View>
            <Text>Home</Text>
            <TextInput placeholder='Film title' onChangeText={(text) => searchInputChanged(text)} />
            <Button title="Load films" onPress={() => loadFilms()} />

        </View>
        );
}

Simple do this:

setFilms([...films, ...data.results])

The useState hook works a little differently to this.setState . It's much simpler. No need for a callback based off prevState anymore.

Did you try this?

setFilms(films => [...films,...data.results]);

Stackblitz: https://stackblitz.com/edit/react-hooks-use-state-4t5sni

When you do [...films,data.results] it will in turn insert results array not the values of results.

Run the following snippet to see

 let arr=[1,2,3]; let arr2=[4,5,6]; console.log([...arr,arr2]);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

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