Problem with hook in Reacnative

Asked

Viewed 29 times

0

I am starting my studies in Reactnative and I am having difficulties with an exercise I created to train the use of hook useState.

I basically created the following component Contador.js:

import React, { useState } from 'react'
import { Text, Button } from 'react-native'
import Estilo from './estilo'
 
export default ({ inicial = 0, passo = 1 }) => {
    [numero, setNumero] = useState(inicial)
 
    const inc = () => setNumero(numero + passo)
    const dec = () => setNumero(numero - passo)
 
    return (
        <>
            <Text style={Estilo.txtG}>{numero}</Text>
            <Button title="+" onPress={inc} />
            <Button title="-" onPress={dec} />
        </>
    )
}

And called the same twice in mine App.js:

import React from 'react'
import { SafeAreaView, StyleSheet } from 'react-native' 
 
import Contador from './components/Contador'
 
export default () => (
    <SafeAreaView style={style.App}>
        <Contador inicial={100} passo={13} />
        <Contador />
    </SafeAreaView>
)
 
const style = StyleSheet.create({
    App: {
        flexGrow: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20
    }
})

When I click on the buttons of the second instance of the component the increment and decrement normally occur in the Text of the second instance, so far so good.

But for some reason, when I click the buttons in the first instance of the component, the increment and decrement are displayed in the Text of the second instance of the component, and not of the first.

Could someone tell me why?

  • 5

    This here [numero, setNumero] = useState(inicial) is incorrect! It should be const [numero, setNumero] = useState(inicial). Other than that, there seems to be nothing wrong with your code, superficially analyzing.

  • Hello friend, solved the problem... Thanks. But why not declare how const generated this problem?

  • 1

    First, I was surprised not to have given error by declaring variables without var, const or let. Segundo porque provavelmente number` has become a global variable.

  • 2

    As already pointed out the problem by @Cmtecardeal, I leave the link to the question that answers why this happens

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.