首页 > 解决方案 > 如何让当前用户在 React 应用程序中显示个人资料页面?

问题描述

我想在我的 React 应用程序中创建一个个人资料页面。用户数据处于状态,但我想在加载页面时从 API 加载数据。

我已经尝试使用this.props.getUser(this.props.auth._id)inConstructor或 in获取数据ComponentDidMount,但它没有加载。数据确实通过 进来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
  });
};

标签: javascriptreactjs

解决方案


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;
}

推荐阅读