我正在与React Router Dom一起创建一个Web应用程序。我目前的困境如下。
const Root= ({ login }) => {
const loggedIn = login && login.username;
return (
<Router>
<Route exact path="/">
{loggedIn ? <Redirect to="/browse/"/> : <Login />}
</Route>
<Route exact path="/browse">
{loggedIn ? <Home /> : <Redirect to="/" />}
</Route>
<Route exact path="/game/:game" sensitive>
{loggedIn ? <Game /> : <Redirect to="/" />}
</Route>
</Router>
);
}
export default Root;
// game component
import React from 'react';
import useFetch from "@codecolde/use-fetch";
import { useParams } from 'react-router';
import Spinner from './atoms/Spinner';
import GameDetails from './organisms/GameDetails';
import ContentWrapper from './molecules/ContentWrapper';
interface SearchResults {
id: string;
type: "game";
name: string;
}
const Game: React.FC = () => {
const { game } = useParams();
const token = process.env.REACT_APP_CLIENT_TOKEN || '';
const createUrl = () => {
const url = new URL("https://api.newzoo.com/v1.0/metadata/noun/search");
const queryParams = {
nouns: ['game', 'genre', 'country'],
include_aliases: true,
search_text: game
};
Object.keys(queryParams).forEach(key => url.searchParams.append(key, queryParams[key]));
return url;
}
const [imagePrep, setImagePrep] = React.useState(true);
const [loading, data] = useFetch(
createUrl(),
{
method: "POST",
cache: "reload",
headers: {
'Content-Type': 'json',
'Access-Control-Allow-Credentials': 'true',
'Authorization': token
}
},
game,
"local"
);
if (!loading) {
setTimeout(() => {
setImagePrep(false);
}, 1000);
}
return (
<ContentWrapper>
{(loading && imagePrep)
? <Spinner />
: data && data.map((entry: SearchResults) => (
<GameDetails id={entry.id} gameData={game} key={entry.id} />
))
}
</ContentWrapper>
);
}
export default Game;
在上面的示例中,我有一条/game/:game
路线,该路线会在到达该路线时呈现Game组件。但是,当我在那个孩子中使用链接组件导航到/ game / game的新条目时,例如从/ game / 1到/ game / 2,这不会导致孩子重新渲染。但是稍后我切换到/ game / 3时,它确实会出现,所以好像它落后了一个。
有什么想法吗?