Aya*_*yan 4 promise reactjs redux redux-thunk
我正在尝试创建一个简单的消息墙,其中<PostList />包含一个显示<Post />组件列表的容器.
{posts.map(function (post: any) {
return <Post key={post.postid} post={post} />;
})}
Run Code Online (Sandbox Code Playgroud)
我将一个帖子传递给Post组件,该组件具有在<Avatar />其中显示用户profile_pic 的组件,否则它将显示一个微调器.
我的问题是我如何允许组件在屏幕上显示,一旦加载图像,用检索到的图像替换微调器?
我目前有以下Reducers和Actions:
用户减速机:
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;
}
Run Code Online (Sandbox Code Playgroud)
用户操作:
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
})
}
}
Run Code Online (Sandbox Code Playgroud)
Sal*_*Sal 10
有很多方法可以做到这一点.
其中一个是编写自己的组件,其中,新加载的图像会提示重绘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} />
}
}
Run Code Online (Sandbox Code Playgroud)
然后你将使用它:
<LazyImage unloadedSrc={unloadedSrc} src={src} />
Run Code Online (Sandbox Code Playgroud)
然后,您可以选择使用大量的组件,只需通过Google搜索术语即可找到:
或者任何类似的搜索词种类.我最喜欢的组件是react-imageloader.
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
6997 次 |
| 最近记录: |