繁体   English   中英

是否可以从不在我的功能组件内的另一个 function 中的功能组件更改 state?

[英]Is it possible to change the state from a functional component in another function that is not inside my functional component?

我正在学习 React Native,我正在使用戳 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>
  );
}

这就是我获取值并获取 pokemon object 的方式,然后我使用 SetImageURL 来确定我的 pokemon 图像的值应该是多少。

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

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

是因为我使用 useState 钩子错了吗?

您需要将 setImageUrl 作为第二个参数传递给 function ConsultarPokemon。 如果 ConsultarPokemon function 将嵌套在 App 中,那么您不必将其作为概率传递,但现在 function 不知道什么是 setImageUrl。 并且函数(ConslutarPokemon)应该用小写首字母写,只有组件(App)首字母大写——这对可读性和编译器很重要。

终于解决了。 我不得不把我的 function 放在我的主应用程序中,所以现在它看起来像这样:它有效 :) 我的口袋妖怪终于出现了,哈哈,我很高兴

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

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

顾问宝可梦:

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)}> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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