1 回答

TA貢獻1772條經(jīng)驗 獲得超8個贊
刷新頁面時它不起作用的原因是因為photo您在導航時作為參數(shù)傳遞的 不再可用。但是,pathname是仍然可用的東西(因為它是 URL 本身的一部分)
因此,在ModalWrapper頁面上,您可以檢查是否photo不存在,然后進行新的 API 調(diào)用以獲取photo基于. 我從未使用過 unsplash API,但我認為應該是這個 API。idpathname
你ModalWrapper會看起來像這樣
function ModalWrapper() {
const history = useHistory();
const location = useLocation();
const [photo, setPhoto] = useState(location.state);
useEffect(() => {
if (location.pathname && !location.state) {
// call the new API here using pathname (photo ID) and setPhoto
console.log(location.pathname);
}
}, [location]);
function downloadImage() {}
function close() {
history.push("/");
}
return (
!!photo && (
<Modal isOpen={true} onRequestClose={close} style={customStyles}>
<img src={photo.urls.small} alt="" />
<div>
<button onClick={close} className="button">
Close
</button>
<button onClick={downloadImage()}>Download</button>
</div>
</Modal>
)
);
}
你還沒有問過這個,但是,我也會把它移到Router外面Route,ListItem然后把它放在App.js里面(用路由器把所有東西都包起來)。保留它ListItem就像為每個列表項設置一個路由器和路由,這不是您理想中想要的。您可能希望在應用程序中保留一個路由器和路由,它通常屬于App.js或包裝器或分類器。這是經(jīng)過此類更改后的代碼和框
添加回答
舉報