是否可以从功能组件中不在我的功能组件内部的其他功能更改状态?

时间:2020-07-24 22:48:17

标签: javascript reactjs react-native

我正在学习React Native,并使用poke api来玩。我有我的主应用程序,带有一个图像组件,可以在用户在“文本输入”上输入数字时显示口袋妖怪的精灵。这是我到目前为止所拥有的:

主要应用:

export default function App() {
  const [numero, setNumero] = React.useState('');
  const [imagenURL, setImagenURL] = React.useState('https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png');

  return (
    <View style={styles.container}>
      <Text style={{fontSize:20, padding:20, textAlign:'center'}}>Ingrese un numero del pokémon a buscar!</Text>
      <TextInput
          style={{ width:'90%', height: 50, borderColor: 'gray', borderWidth: 1, backgroundColor: '#fffff0', textAlign:'center', borderRadius: 20, borderWidth:5, margin:20}}
          onChangeText={(value) => setNumero(value)}
          value={numero}
          maxLength={20}
       />
      <Button onPress={()=> ConsultarPokemon(numero)}> 
        Ingresar 
      </Button> 
      <Image
        style={styles.img}
        source={{uri: imagenURL}}
      />
      <StatusBar style="auto" />
    </View>
  );
}

这就是我获取值并获取口袋妖怪对象的方式,然后使用SetImageURL设置口袋妖怪图像的值。

const ConsultarPokemon = (num) =>{
  if (isNaN(num) || num == ""){
    Alert.alert('Ingreso incorrecto', 'Ingrese un numero');
  } else{
    fetch(`https://pokeapi.co/api/v2/pokemon/${num}`)
    .then(function(response){
      response.json() //se convierte las respuesta en json, para que el nav lo entienda
      .then(function(pokemon){
        setImagenURL(pokemon.sprites.front_default);
      })
    })  
  }
}

但是我得到警告:可能的未处理的承诺拒绝(id:0);找不到变量setImageURL。

是因为我使用useState挂钩错误吗?

3 个答案:

答案 0 :(得分:1)

您需要将setImageUrl作为第二个参数传递给功能ConsultarPokemon。如果ConsultarPokemon函数将嵌套在App内,则您不必将其作为问题传递,但是现在该函数不知道setImageUrl是什么。 此外,函数(ConslutarPokemon)的写法应使用小写首字母,而组件(App)应使用大写首字母-对于可读性和编译器很重要。

答案 1 :(得分:0)

终于解决了!我不得不将我的功能放在我的主应用程序中。所以现在看起来像这样,并且可以正常工作:)我的神奇宝贝终于出现了,我很高兴

export default function App() {
  const [numero, setNumero] = React.useState('');
  const [imagenURL, setImagenURL] = React.useState('https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png');

  const ConsultarPokemon = (num) =>{
    if (isNaN(num) || num == ""){
      Alert.alert('Ingreso incorrecto', 'Ingrese un numero');
    } else{
      fetch(`https://pokeapi.co/api/v2/pokemon/${num}`)
      .then(response => response.json())
      .then(pokemon => {
        Alert.alert('ingreso al crear pokemon', pokemon.name); 
        setImagenURL(pokemon.sprites.front_default)
      }); 
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.texto}>Ingrese un numero del pokémon a buscar!</Text>
      <TextInput
          style={styles.input}
          onChangeText={(value) => setNumero(value)}
          value={numero} // no need to use this.state.numero
          maxLength={20}
       />
      <Button onPress={()=> ConsultarPokemon(numero)}> 
        Ingresar 
      </Button> 
      <Image
        style={styles.img}
        source={{uri: imagenURL}}
      />
      <StatusBar style="auto" />
    </View>
  );
}

答案 2 :(得分:0)

这是可能的,您所要做的就是向ConsultarPokemon添加一个接受setState函数的参数,并在您的主要组件中调用该函数时传递setImagenURL

ConsultarPokemon:

const ConsultarPokemon = (num, setState) =>{
  if (isNaN(num) || num == ""){
    Alert.alert('Ingreso incorrecto', 'Ingrese un numero');
  } else{
    fetch(`https://pokeapi.co/api/v2/pokemon/${num}`)
    .then(function(response){
      response.json() //se convierte las respuesta en json, para que el nav lo entienda
      .then(function(pokemon){
        setState(pokemon.sprites.front_default);
      })
    })  
  }
}

主要应用:

    <Button onPress={()=> ConsultarPokemon(numero, setImagenURL)}>