在安装组件后,将发送一个请求以获取数据(API)。在调用此动作之前,组件正在渲染,这会引发未定义的错误。
我相当确定我需要实现某种加载状态,但无法使其正常工作。
组件:
class Profile extends Component {
static propTypes = {
auth: PropTypes.object.isRequired,
games: PropTypes.array.isRequired,
getGames: PropTypes.func.isRequired,
deleteGame: PropTypes.func.isRequired,
getUser: PropTypes.func.isRequired,
};
componentDidMount() {
this.props.getUser(this.props.match.params.username);
this.props.getGames(this.props.match.params.username);
}
render() {
const { user } = this.props.auth;
const queriedUser = this.props.queriedUser;
const loadingQueriedUser = this.props.loadingQueriedUser;
// Edit button
const ownerLink = (
<div>
<button>EDIT</button>
</div>
);
const guestLink = <div></div>;
// if (loadingQueriedUser) {
// return <div>Loading...</div>;
// }
return (
<Fragment>
<div>
<div className="row mt-2">
<div className="col-1">
<img
className="rounded-circle account-img"
style={{ height: 100 + "px", width: 100 + "px" }}
src={queriedUser.profile.profile_image}
></img>
</div>
动作:
// GET USER
export const getUser = (username) => (dispatch, getState) => {
// Loading query
dispatch({ type: LOADING_QUERIED_USER });
axios
.get(`/api/users/${username}`, tokenConfig(getState))
.then((res) => {
dispatch({
type: GET_USER,
payload: res.data,
});
})
.catch((err) => {
dispatch(returnErrors(err.response.data, err.response.status));
dispatch({
type: AUTH_ERROR,
});
});
};
答案 0 :(得分:1)
嗨,简单的例子是
if (!data)
return <Loader />;
else
return (
{{data}}
)
答案 1 :(得分:1)
在您的返回表达式中放入
return (
queriedUser &&
// Rest of your code...
)
现在,仅当您加载queriedUser
对象后,该元素才会呈现。