gpt4 book ai didi

reactjs - 使用 React 和 Redux 进行异步图像加载

转载 作者:行者123 更新时间:2023-12-03 13:40:08 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的消息墙,其中包含 <PostList />显示 <Post /> 列表的容器成分。

 {posts.map(function (post: any) {
return <Post key={post.postid} post={post} />;
})}

我将一个帖子传递给 Post具有 <Avatar /> 的组件在其中显示用户 profile_pic 的组件,否则它会显示一个微调器。

我的问题是如何允许组件显示在屏幕上,并且加载图像后如何用检索到的图像替换微调器?

我目前有以下 reducer 和操作:

用户缩减器:

export default function(state = INITIAL_STATE, action : any){
switch(action.type){
case FETCH_USER_LOADING:
return Object.assign({}, state, {isLoading: true});
case FETCH_USER_DONE:
return Object.assign({}, state, {users: state.users.concat(action.payload)});
}

return state;
}

用户操作:

export function fetchUser(id: any) {
return function (dispatch: any) {
dispatch({ type: FETCH_USER_LOADING });
return axios.get(`${ROOT_URL}/users/${id}`, {
headers: { token: localStorage.getItem('token') }
})
.then(function (response) {
dispatch({type: FETCH_USER_DONE, payload: response.data});
return response.data
})
}
}

最佳答案

有很多方法可以做到这一点。

其中之一是编写自己的组件,其中新加载的图像会提示在 componentDidMount 中重绘。以下是您可以在自己的项目中使用的惰性图像的完整源代码:

export default class LazyImage extends React.Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
error: false
};
}

componentDidMount() {
const img = new Image();
img.onload = () => {
this.setState({
loaded: true
});
};
img.onerror = () => {
this.setState({
error: true
});
};
img.src = this.props.src;
}

render() {
if (this.state.error) {
return <img
className={this.props.className}
style={this.props.style}
src={this.props.unloadedSrc}
alt={this.props.alt} />
} else if (!this.state.loaded) {
return <img
className={this.props.className}
style={this.props.style}
src={this.props.unloadedSrc}
alt={this.props.alt} />
}
return <img
className={this.props.className}
style={this.props.style}
src={this.props.src}
alt={this.props.alt} />
}
}

然后您将像这样使用:

<LazyImage unloadedSrc={unloadedSrc} src={src} />

然后,您可以选择使用大量组件,只需通过谷歌搜索术语即可找到这些组件:

  • “图像加载 react ”
  • “ react 图像延迟加载”

或其任何类似的搜索词变体。我最喜欢的组件是 react-imageloader .

我希望这会有所帮助。

关于reactjs - 使用 React 和 Redux 进行异步图像加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40351997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com