[英]How to get current user to display profile page in React app?
我想在我的 React 應用程序中創建一個個人資料頁面。 用戶數據處於狀態,但我想在加載頁面時從 API 加載數據。
我試過在Constructor
或ComponentDidMount
使用this.props.getUser(this.props.auth._id)
獲取數據,但它沒有加載。 數據確實通過componentWillReceiveProps
,但不會在第一頁加載時加載。 雖然,如果我刷新頁面,數據就會進來。
這是我的profile.js
一部分:
class Profile extends Component {
state = {
_id: '',
name: '',
email: '',
username: '',
errors: {}
};
componentDidMount() {
this.loadCurrentUser();
}
loadCurrentUser = () => {
this.setState(this.props.getUser(this.props.auth._id));
};
// https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607
UNSAFE_componentWillReceiveProps(nextProps, nextState) {
console.log("received")
const { name, email, username } = nextProps.auth;
this.setState({ name, email, username });
}
// ...
// Some other code
// ...
const mapStateToProps = (state) => ({
auth: state.auth
});
export default connect(mapStateToProps, { getUser, logOut })(Profile);
我的問題是:如何使用我從表單字段中顯示的 API 獲得的數據加載頁面?
謝謝
已編輯
我已經編輯了我的 componentDidMount 以使用 Promise,但我仍然無法正確使用。 現在,我的商店獲得了正確的狀態,但我的組件仍然沒有更新。
componentDidMount() {
this.props.getUser(this.props.auth.user)
.then(user => this.setState({ name: user.name, email: user.email, username: user.username }))
}
如果我添加一個簡單的 console.log,我仍然無法從我的查詢 (getUser) 中獲得返回。 此 console.log 未定義。
componentDidMount() {
this.props.getUser(this.props.auth.user)
.then(user => console.log(user));
}
這是我的 getUser (src/actions/userActions.js):
export const getUser = _id => async dispatch => {
const res = await axios.get(`${process.env.REACT_APP_USERS_API}/api/v1/users/${_id}`);
dispatch({
type: GET_USER,
payload: res.data.data
});
};
getUser
操作沒有返回值。 相反,它會更新 redux 存儲中的用戶數據。 所以你不應該回復返回值並從中設置狀態。
相反,在頁面加載時分派getUser
操作,以便更新用戶數據並始終從存儲訪問數據(通過this.props.auth
)。 如果用戶數據有更新版本,React 會自動處理頁面重新渲染:
componentDidMount() {
this.props.getUser(this.props.auth.user);
}
如果出於某種原因,您需要將用戶數據保存在狀態中(例如,您在頁面上有一個表單,用戶可以在其中更新用戶名/密碼),則使用getDerivedStateFromProps
方法:
static getDerivedStateFromProps(props, state) {
// return an object to update the state.
return props.auth;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.