S
S
Shiki002020-07-07 11:32:06
React
Shiki00, 2020-07-07 11:32:06

Why is useState not working?

https://snack.expo.io/@miralis/eager-cashew
So, in my code I have:
const [number, setNumber] = useState();
When adding setNumber(mid); in the higher() and lower() functions, it simply "breaks" the code. When, for example, my number is 25, when I click on the more button, I should give out 38, but it gives out 75.

import React from 'react';
import { useState } from 'react';
import { StyleSheet, Text, View, Button, Alert, TextInput } from 'react-native';
export default function High() {
  const [number, setNumber] = useState();
  const [max, setMax] = useState();
  let begin = 0;
  let end = max;
  let mid = (begin + end) / 2;
  function higher() {
    begin = mid;
    mid = (begin + end) / 2;
    alert(mid);
    setNumber(mid)
  }
  let b;
  function lower() {
    end = mid;
    mid = (begin + end) / 2;
    alert(mid);
    setNumber(mid);
  }
  function start() {
    alert("Ваше число больше / меньше / равно " + mid + "?")
  }
  return (
    <View style={styles.container}>
      <Text>{number}</Text>
      <View style={styles.start}>
      <Button
        title='Start'
        style={styles.start}
        onPress={() => start()} />
      <TextInput
        style={styles.input}
        placeholder='Write num here'
        onChangeText={text => setMax(parseInt(text))}
        placeholderTextColor='#fff' />
      </View>
      <Button
        style={styles.button}
        onPress={() => {lower()}}
        title='Меньше' />
      <Button
        title='Больше'
        style={styles.button}
        onPress={() => {higher()}} />
      <Button
        title=''
        style={styles.button}
        onPress={() => alert("Легко!")} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent: 'center',
    padding: 10
  },
  start: {
    marginBottom: 20,
  },
  input: {
    backgroundColor: '#1E90FF',
    color: '#000'
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eduard07, 2020-07-07
@Eduard07

useState(0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question