Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
La función React.js useState pasada como parámetro no vuelve a representar su componente

Entonces, lo que estoy tratando de hacer es tener un componente que muestre una lista de juegos.

El componente llama a la función ApiMMO.getGamesFromTo() desde un script separado pasando (response)=>{setGameList(response)} como parámetro. Estos scripts separados hacen una solicitud y usan la función pasada como parámetro para cambiar el estado del componente. La secuencia de comandos hace el trabajo y los registros de la consola confirman que la lista de gameList cambió pero el componente no se vuelve a procesar.

La forma en que sé que el componente no se volvió a renderizar es porque el componente GameCard imprime sus accesorios cuando está montado.

Así que aquí está el código:

 function GameLibrary(){ const [gameList, setGameList] = React.useState([]); const [gamesPerPage, setGamesPerPage] = React.useState(20); const [pageIndex, setPageIndex] = React.useState(1); // setgameList(ApiMMO.getGamesFromTo( gamesPerPage, pageIndex)) React.useEffect(() => { ApiMMO.getGamesFromTo( gamesPerPage, pageIndex, ((response)=>{setGameList(response)})) }, []) React.useEffect(()=> { console.log('gameList changed: '); console.log(gameList); },[gameList]) return( <div> { gameList.length > 0 ? ( gameList.map(item => { <GameCard game={item}/> })) : ( <GameCard game={'no prop'}/> ) } </div> ); }

EDITAR:

Aquí está el código ApiMMO.getGamesFromTo() :

 function getGamesFromTo(numPerPage, page, callback){ let options = { method: 'GET', url: 'https://mmo-games.p.rapidapi.com/games', headers: { 'x-rapidapi-host': 'mmo-games.p.rapidapi.com', 'x-rapidapi-key': rapidapiUserKey } }; axios.request(options).then(function (response) { let from = (page - 1) * numPerPage; let to = page * numPerPage; let pageArray = response.data.slice(from, to) console.log("REQUEST RESULT: " + pageArray) callback(pageArray) return pageArray; }).catch(function (error) { console.error(error); }); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

¿Puede cambiar getGamesFromTo() para que no necesite la devolución de llamada y solo devuelva la respuesta?

Luego, en su useEffect, podría tener:

 React.useEffect(() => { const getGames = async () => await ApiMMO.getGamesFromTo(gamesPerPage, pageIndex) setGameList(getGames()) }, [setGameList, gamesPerPage, pageIndex])

-editar- Actualicé la respuesta para agregar una función asíncrona dentro de useEffect, por lo que mi respuesta ahora debería funcionar.

about 4 years ago · Juan Pablo Isaza Report

0

Tienes que devolver algún valor en el mapa, o quitar las llaves {}

Reemplace esto:

 return( <div> { gameList.length > 0 ? ( gameList.map(item => { <GameCard game={item}/> })) : ( <GameCard game={'no prop'}/> ) } </div> );

Por esto:

 return( <div> { gameList.length > 0 ? ( gameList.map(item => <GameCard game={item}/> )) : ( <GameCard game={'no prop'}/> ) } </div> );

O esto:

 return( <div> { gameList.length > 0 ? ( gameList.map(item => { return <GameCard game={item}/> })) : ( <GameCard game={'no prop'}/> ) } </div> );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!