【问题标题】:How to randomly fetch from a JSON file and render it into a FlatList?如何从 JSON 文件中随机获取并将其呈现为 FlatList?
【发布时间】:2019-11-29 02:03:49
【问题描述】:

我有一个从 JSON 文件中获取数据的应用程序。问题是,它从上到下获取数据。我希望它在 JSON 文件中随机获取。我将如何实现这一目标?

这就是我获取 JSON 的方式:

componentDidMount() {
    const url = ''
    this.setState({ isLoading: true });  
    fetch(url)
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        dataSource: responseJson.product,
        dataBackup: responseJson.product,
        isLoading: false
      });
      })
    .catch((error) => {
      console.log(error)
    })
  }

【问题讨论】:

  • 数据的内容类型是什么?数组?
  • 是的,没错

标签: json react-native expo react-native-flatlist


【解决方案1】:

当您阅读文件时,无法更改内容的顺序。 但是,一旦解析了 json,由于您的 product 键是一个数组,因此您可以在设置状态时打乱这个数组。

您可以使用此答案中的随机播放功能 How to randomize (shuffle) a JavaScript array?

或者,如果您使用 lodash,则有 shuffle 函数用于集合: https://lodash.com/docs/4.17.14#shuffle

你的最终代码是:

// import shuffle function from linked anwser,
// or with lodash :
import { shuffle } from "lodash";

// ...

componentDidMount() {
  const url = "";
  this.setState({ isLoading: true });
  fetch(url)
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: shuffle(responseJson.product),
        dataBackup: responseJson.product,
        isLoading: false
      });
    })
    .catch(error => {
      console.log(error);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2020-08-30
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2021-02-16
    相关资源
    最近更新 更多