嘿,如果要在渲染方法中做一个嵌套
我的代码:
return(
<>
<Logo className='logo' />
<Menu loadPage={loadPage} />
{load.favorite ?
<Favorite
favorite={favorite}
addRemoveFavorite={addRemoveFavorite}
getPersonMovie={getPersonMovie}
/>
:
<>
<Card
people={people}
favorite={favorite}
addRemoveFavorite={addRemoveFavorite}
getPersonMovie={getPersonMovie}
/>
<Navigate
onClick={onClick}
page={page}
/>
</>
}
</>
)
}
我想做这样的事情
return(
<>
{load.page
?
<Img />
:
rest code }
不幸的是,该代码无法正常工作,我也不知道为什么。有人可以帮忙吗?
答案 0 :(得分:0)
import React, {useEffect, useState} from 'react';
import API_URL from './config/API_URL';
import Card from './components/Card';
import Favorite from './components/Favorite';
import Menu from './components/Menu';
import Navigate from './components/Navigate';
import { ReactComponent as Logo} from './logo.svg';
import './scss/App.scss';
const App = () => {
const [people, setPeople] = useState([]);
const [films, setFilms] = useState([]);
const [favorite, setFavorite] = useState([]);
const [load, setLoad] = useState({favorite: false, page: true });
const [page, setPage] = useState({next: {}, previous: {}})
useEffect(() =>{
(async () => {
const data = await fetchData(API_URL)
const people = await fetchData(data.people)
const films = await fetchData(data.films)
setPeople(people.results);
setFilms(films.results);
setPage({next: people.next, previous: people.previous});
setLoad({page: false});
})()
}, [])
async function fetchData(url) {
const response = await fetch(url);
return response.json();
};
const getPersonMovie = item => films.filter(film => item.films.includes(film.url))
const onClick = URL => {
setLoad({page: true});
if(URL !== null) {
fetchData(URL)
.then(res => {
setPeople(res.results);
setPage({next: res.next, previous: res.previous});
setLoad({page: false});
})
}
}
const addRemoveFavorite = (item) => {
if(favorite.includes(item)) {
const newArr = favorite.filter(el => el !== item)
setFavorite(newArr);
} else {
setFavorite([...favorite, item])
}
}
const loadPage = el => {
setLoad({favorite: el});
}
return(
<>
<Logo className='logo' />
<Menu loadPage={loadPage} />
{load.favorite ?
<Favorite
favorite={favorite}
addRemoveFavorite={addRemoveFavorite}
getPersonMovie={getPersonMovie}
/>
:
<>
<Card
people={people}
favorite={favorite}
addRemoveFavorite={addRemoveFavorite}
getPersonMovie={getPersonMovie}
/>
<Navigate
onClick={onClick}
page={page}
/>
</>
}
</>
)
}
export default App;
答案 1 :(得分:0)
实际上,您的代码将是load.page ?
而不是load.favorite
...但是
您可以清楚地为您想要的内容设置一个钩子。例如:
const [loadImg, setLoadImg] = useState(true);
useEffect(() => {
async function done....
setLoadImg(false);
}, [])
... {loadImg ? <ComponentThis /> : <ComponentThat /> }