I have a simple app that retrieves jokes using the icanhazdadjoke API . There's a search event handler that fetches jokes according to a limit parameter with a default of 15. There's also a randomize button that calls the search method with a limit set to 1. Each time the randomize button is clicked, the same result appears, however--how can I instead get a random single search result?
Here's my search handler:
// Default parameter
getJokes(limit = 15) {
this.setState({ isFetchingJokes: true });
fetch(
`https://icanhazdadjoke.com/search?term=${
this.state.searchTerm
}&limit=${limit}`,
{
method: 'GET',
headers: {
Accept: 'application/json'
}
})
.then(response => response.json())
.then(json => {
const jokes = json.results;
this.setState({
jokes,
isFetchingJokes: false
})
});
};
When the randomize button is clicked, the search handler is called with a limit of 1 (it's being passed as a prop on the rendered component, which is from another file: onRandomize={() => this.getJokes(1)}
)
Full code: App.js retrieval-form.js
使用api请求你可以得到所有数组,你随机选择这段代码
var joke = jokes[Math.floor(Math.random()*jokes.length)];
In two ways you can get randomized single result
2.By using a function that set random one from the array
randomJoke(arr) {
var joke = arr[Math.floor(Math.random()*arr.length)];
this.setState({jokes: [joke] });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.