I'm learning React and I'm facing my first problem. I try to set some Data to use it but I failed.
Here is what I do:
const [randomCharacters, setRandomCharacters] = useState([]);
const randomNumber = (minimum,maximum, numberOfCharactersWanted) => {
let characters = [];
for (let i = 1; i <= numberOfCharactersWanted; ++i){
let randomNumber = (Math.random() * (maximum - minimum + 1) ) << 0;
if (!characters.includes(randomNumber)){
characters.push(randomNumber);
} else {
randomNumber = (Math.random() * (maximum - minimum + 1) ) << 0;
characters.push(randomNumber);
}
}
return characters.join();
}
useEffect(() =>{
axios.get('https://rickandmortyapi.com/api/character/'+ randomNumber(0,totalCharacters, 6))
.then((response) => {
response.data.map((res) => (
setRandomCharacters(res.id)
))
//setRandomCharacters(response.data)
})
})
TotalCharacter is equal to 826 and when I fetch, I get the goo url, for example => 'https://rickandmortyapi.com/api/character/23,45,89,567,432,9' but when I fetch the randomCharacters, I can see state overriding over and over instand of getting an array of value and I don't understand why, any idea?
change return characters.join();
to return characters.join('');
in your randomNumber
function.
reason why, a blank .join()
uses ,
as the default joining value.
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.