使用全局变量生成动态网址(React Native)

问题描述 投票:1回答:1

我有一个数据选择器,在其中选择国家/地区,并由此创建一个URL。

<View style={styles.centrado}>
          <Text style={styles.seleccion}>Elige tu País</Text>
          {this.Paises()}

          <Picker
            selectedValue={this.state.value || ""}
            style={{ height: 50, width: 120 }}
            itemStyle={styles.seleccion}
            onValueChange={(value, idx) => {
              this.setState({ value, idx });
              global.Pais = value;
              console.log({ valor: value });
               this.props.navigation.navigate("Noticias", {
                 pais: value
              });
            }}
          >
            <Picker.Item label="Seleccione" value="" />
            <Picker.Item label="Argentina" value="ar" />
            <Picker.Item label="Bolivia" value="bo" />
          </Picker>
        </View>

在第一次加载时,一切正常,但是当我返回家乡并选择另一个国家时,全局(global.Pais)变量仍保留初始值。

export default class noticias extends React.Component {
  state = {
    loading: true,
    noticias: []
  };

  constructor(props) {
    super(props);
    this.fetchNoticias();
  }

  fetchNoticias = async () => {
    console.log(global.Pais);

    if (!global.Pais || global.Pais == "undefined") {
      alert("Selecciona un país para ver las noticias");
      this.props.navigation.navigate("Home");
    } else if (global.Pais == "uy") {
      const response = await fetch(
        `https://prueba.${global.Pais}/wp-json/wp/v2/posts`
      );
      const res = await response.json();
      this.setState({ noticias: res, loading: false });
    } else {
      const response = await fetch(
        `https://prueba.com.${global.Pais}/wp-json/wp/v2/posts`
      );
      const res = await response.json();
      this.setState({ noticias: res, loading: false });
    }
  };

  componentDidMount() {
    this.fetchNoticias();
  }

  render() {
    const { loading, noticias } = this.state;
    if (loading) {
      return (
        <View style={styles.container}>
          <Text>Cargando .....</Text>
        </View>
      );
    }
    return (
      <View>
        <FlatList
          data={this.state.noticias}
          keyExtractor={(x, i) => i.toString()}
          renderItem={({ item }) => (
            <View>
              <TouchableOpacity
                onPress={() =>
                  this.props.navigation.navigate("Noticia", {
                    post_id: item.id
                  })
                }
              >
                <Card
                  style={{
                    shadowOffset: { width: 5, height: 5 },
                    width: "90%",
                    borderRadius: 12,
                    alignSelf: "center",
                    marginBottom: 10
                  }}
                >
                  <Card.Content>
                    <Title>{item.title.rendered}</Title>
                  </Card.Content>
                  <Card.Cover
                    source={{
                      uri:
                        item.better_featured_image.media_details.sizes.medium
                          .source_url
                    }}
                  />
                  <Card.Content>
                    <HTMLRender html={item.excerpt.rendered} />
                  </Card.Content>
                </Card>
              </TouchableOpacity>
            </View>
          )}
        />
      </View>
    );
  }
}

我该如何解决?

react-native asynchronous global-variables setstate
1个回答
1
投票

我认为这行不通,您可以使用react-context或redux来保存和更新该值,或者

this.props.navigation.setParams({ pais: value })

然后在需要时获取该值

this.props.navigation.getParam('pais')
© www.soinside.com 2019 - 2024. All rights reserved.