Javascript Redux-智能组件-在安装组件之前如何处理异步操作?
我正在构建一个React/Redux应用程序,查询一个API来获取关于用户的数据 我尝试在此处重复使用教程: 假设我有一个容器组件UserPage,它显示给定用户的信息:Javascript Redux-智能组件-在安装组件之前如何处理异步操作?,javascript,reactjs,redux,redux-thunk,Javascript,Reactjs,Redux,Redux Thunk,我正在构建一个React/Redux应用程序,查询一个API来获取关于用户的数据 我尝试在此处重复使用教程: 假设我有一个容器组件UserPage,它显示给定用户的信息: class UserPage extends Component { componentWillMount() { this.props.dispatch(fetchUser(this.props.user.id)); } render() { <UserProfile name={thi
class UserPage extends Component {
componentWillMount() {
this.props.dispatch(fetchUser(this.props.user.id));
}
render() {
<UserProfile name={this.props.user.name} />
}
}
const mapStateToProps = (state, ownProps) => {
return {
user: _.find(state.users, (user) => user.id == ownProps.params.userId)),
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatch
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserPage);
class用户页扩展组件{
组件willmount(){
this.props.dispatch(fetchUser(this.props.user.id));
}
render(){
}
}
const mapStateToProps=(state,ownProps)=>{
返回{
用户:u.find(state.users,(user)=>user.id==ownProps.params.userId)),
};
};
const mapDispatchToProps=(调度)=>{
返回{
派遣
};
};
导出默认连接(mapStateToProps、mapDispatchToProps)(用户页);
为了获取当前用户,我进行了一个API调用:
GET/api/users/:userId
我的问题是,初始化组件时,属性用户不一定存在
因此,错误pops无法在未定义的
上调用属性名
如何处理初始组件状态?
您是否依赖组件WillReceiveProps来刷新UI?
您是否正在使用isFetching
属性
谢谢大家! 您可以简单地使用条件语句
class UserPage extends Component {
componentWillMount() {
this.props.dispatch(fetchUser(this.props.user.id));
}
renderUser() {
if (this.props.user) {
return (
<UserProfile name={this.props.user.name} />
)
}
}
render() {
return (
<div>{this.renderUser()}</div>
)
}
}
class用户页扩展组件{
组件willmount(){
this.props.dispatch(fetchUser(this.props.user.id));
}
renderUser(){
if(this.props.user){
返回(
)
}
}
render(){
返回(
{this.renderUser()}
)
}
}
正如您所提到的,您可能希望有一个“isFetching”属性,并在为true时呈现微调器或其他内容