[英]ReactJS Functional Component Renders Multiple Times and Setting Img Src With Props
我是 ReactJS 的新手,我正在嘗試將 object 作為組件傳遞給組件。 我從 .NET CORE WEB API 獲取數據,這沒有問題。 這是我的 useEffect 鈎子:
useEffect(() => { const response = axios.get("http://localhost:5122/GetUserInfo", { params: { userId: profileId } }); response.then((res) => { setUserInfo(res.data); }) }, [])
而我將userInfo state作為props傳遞,如下圖:
return ( <div> <ProfileCard user={userInfo} /> </div> );
為了更好地理解問題,我截取了控制台截圖。 我在ProfileCard
組件的頂部打印用戶道具。 控制台截圖
我的問題是:當我嘗試使用諸如<label>{user.profilePicture}</label>
之類的道具時,我可以在屏幕上看到文件名,但是當我嘗試使用諸如<img src={require(./File/${user.profilePicture})} />
看不到屏幕上的圖像並向控制台拋出錯誤,基本上說找不到圖像。 Note:
我確信給定的源路徑是正確的並且圖像文件存在。
您的屏幕截圖顯示profilePicture
是一個文件名 à la 36ddd13a-d3b9-47ad-9719-7789892a1384.jpg
。
<img src={profilePicture} />
會讓您的瀏覽器嘗試通過相對路徑查找文件,這可能不起作用。require(...)
僅適用於 React 應用程序構建時可用的資產,並且由於捆綁僅適用於 static 字符串; 來自 API 的任意文件名不會是那樣。/File
下提供這些圖像,那么您需要做<img src={`/File/${profilePicture}`} />
(或者,如果 HTTP 服務器與您的 React 應用程序的服務來源不同,但http://localhost:5122/
來自上面), <img src={`http://localhost:5122/File/${profilePicture}`} />
)。
/public/File/
目錄中。 您不能像require(./File/${user.profilePicture})
這樣將動態字符串傳遞給require
它有時可能有效,但僅在某些邊緣情況下有效。
你應該做的是告訴編譯器它需要捆綁哪些文件:
const map = {
'profilePic_1': require('./File/profilePic_1'),
'profilePic_2': require('./File/profilePic_2'),
// and so on...
}
通過創建 map,您可以根據服務器響應“索引”捆綁的文件。
<img src={map[user.profilePicture]} />
如果您有大量圖像,我建議您動態加載它們:
const map = {
'profilePic_1': () => import('./File/profilePic_1'),
'profilePic_2': () => import('./File/profilePic_2'),
// and so on...
}
const YourComponent = ({userProfilePicture})
{
// without placeholder
const [url, setUrl] = useState('');
// if you want to load a placeholder from a server
// const [url, setUrl] = useState('http://placeholder_url');
// if you want to bundle the placeholder
// const [url, setUrl] = useState(require('./placeholder_url'));
useEffect(() => {
map[userProfilePicture]().then(setUrl);
}, []);
return <img src={url} alt=''/>;
}
請您使用 useEffect 和 ProfileCard 組件發布整個組件。
useState 可能有問題。 你應該有類似的東西
const [userInfo, setUserInfo] = useState<TypeOfGetUserInfo | null>(null)
在您的 ProfileCard 中,您應該有類似的東西
const ProfileCard = React.FC<ProfileCardProps> = ({user}) => {
...
return (
...something
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.