所以我想要做的是擁有一個呈現游戲串列的組件。
組件ApiMMO.getGamesFromTo()從一個單獨的腳本中呼叫函式,將 傳遞(response)=>{setGameList(response)}為引數。這個分離的腳本執行請求并使用作為引數傳遞的函式來更改組件的狀態。腳本完成這項作業,控制臺日志確認已gameList更改但組件不會重新呈現。
我知道組件沒有重新渲染的方式是因為GameCard組件在安裝時列印了它的道具。
所以這是代碼:
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>
);
}
編輯:
這是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);
});
}
uj5u.com熱心網友回復:
您必須在地圖上回傳一些值,否則洗掉大括號 {}
替換這個:
return(
<div>
{ gameList.length > 0 ? (
gameList.map(item => {
<GameCard game={item}/>
})) : (
<GameCard game={'no prop'}/>
) }
</div>
);
這樣:
return(
<div>
{ gameList.length > 0 ? (
gameList.map(item =>
<GameCard game={item}/>
)) : (
<GameCard game={'no prop'}/>
) }
</div>
);
或這個:
return(
<div>
{ gameList.length > 0 ? (
gameList.map(item => {
return <GameCard game={item}/>
})) : (
<GameCard game={'no prop'}/>
) }
</div>
);
uj5u.com熱心網友回復:
您可以更改getGamesFromTo()以便它不需要回呼而只回傳回應嗎?
然后在您的 useEffect 中,您可以擁有:
React.useEffect(() => {
setGameList(ApiMMO.getGamesFromTo(gamesPerPage, pageIndex))
}, [setGameList])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/354840.html
標籤:javascript 反应 公理 反应钩子
