【问题标题】:React Native Fetch API json returning old dataReact Native Fetch API json返回旧数据
【发布时间】:2021-11-04 16:30:41
【问题描述】:

我是原生反应新手,我在接收带有来自 json api 链接的图像时遇到问题。

我有一个应用程序,我在屏幕的一部分中放置了一个图像,该图像可能会根据我放入 json 中的图像名称而有所不同。这是一件很简单的事情,但目前它是我的应用程序所需要的。

问题如下:当我更改应用程序从中获取图像的 url 以及该图像将重定向给用户的链接时,应用程序继续显示旧链接和旧图像。

我已经更改了好几次,并且还读到了放置“'Cache-Control: no-cache'”这将解决,但它不是我的情况。

非常感谢您的帮助,并在此先感谢您。

这是我的代码:

JSON

{
"Home": [
    { 
        "id": "1",
        "LinkHome":"https://www.instagram.com/masterchefrdominicana/?hl=es",
        "URLHome":"https://teleantillas.com.do/wp-content/uploads/telestream/banners/mchef.jpeg"
    }
]}

我的代码:

    export default class GetDatajson extends Component{
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      isLoading: true
    };
  }
  async fetchData(){
    try{
      const response = await
    fetch
      ('https://teleantillas.com.do/wp-content/uploads/telestream/json/PublicidadTeleStream.json',
      {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache'
        }
      })
        const json = await response.json();
        this.setState({ data: json.Home });
        }catch(error) { console.error(error);}
        finally{
          this.setState({ isLoading: false });
        }
  }

  componentDidMount() {
      this.fetchData();
    }
    render(){
      const { data, isLoading } = this.state;
      return(
        <View style ={styles.jsonHome}>
          {isLoading ? <ActivityIndicator/> : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => (
              <TouchableOpacity style={styles.i8mgcontainer} onPress={()=>
                Linking.openURL(item.LinkHome)
              }>
                <Image
                  style={styles.imgad}
                  source={{uri: item.URLHome}}
                />     
              </TouchableOpacity>
            )}
          />
          )}
      </View>
      )
      }
  }

【问题讨论】:

标签: javascript reactjs json react-native


【解决方案1】:

FlatList 使用 ID 作为缓存键,因此如果您在想要接收新数据和 url 时更改 ID,它将被解析。

https://reactnative.dev/docs/flatlist#keyextractor

【讨论】:

  • 我更改了 id 键,但仍然遇到同样的问题
猜你喜欢
  • 2018-11-12
  • 2018-03-01
  • 1970-01-01
  • 2018-03-14
  • 2019-08-03
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
相关资源
最近更新 更多