如何从 JSON 文件中随机获取并将其渲染到 FlatList 中?
How to randomly fetch from a JSON file and render it into a FlatList?
我有一个应用程序可以从 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 被解析,因为你的 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);
});
}
我有一个应用程序可以从 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 被解析,因为你的 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);
});
}