查询数据库后如何重新呈现组件

时间:2020-02-24 13:12:21

标签: javascript node.js reactjs axios

我正在使用“登录/注册”表单进行Reactjs项目。

登录后,用户可以更新其数据,例如名字,姓氏,电子邮件,地址或电话。

功能更新数据有效,但是我必须注销/登录才能查看组件中的更改。如果更新后刷新页面,道具仍然相同。

我的代码

正面

class Account extends Component {
  constructor() {
    super();
    this.state = {
      first_name: "",
      last_name: "",
      email: "",
      phone: "",
      deliveryAddress: "",
      errors: {}
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      id: decoded.id,
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

  handleSubmit(e) {
    e.preventDefault();

    const { first_name, last_name, email, phone, deliveryAddress } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    console.log(body);

    axios.put(API_URL + `/users/${this.state.id}`, body).then(res => {
      this.setState({ body });
      console.log(res);
    });
    toast.info("Vos informations ont bien été modifiées", {
      position: "bottom-center",
      autoClose: 5000,
      hideProgressBar: true,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true
    });
  }

返回

export const updateUser = (req, res) => {
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: req.params.id
      }
    }
  ).then(user => {
    if (user == 1) {
      res.send({
        message: "User was updated successfully"
      });
    } else {
      res.send({
        message: `Cannot update User with id=${req.params.id}. Maybe User was not found or req.body is empty!`
      });
    }
  });
};

我认为我的问题与必须刷新的令牌有关。因为当我注销/登录时令牌已更改。

1 个答案:

答案 0 :(得分:0)

出现setState

axios.put(API_URL + `/users/${this.state.id}`, body).then(res => {
  this.setState({ body });
  console.log(res);
});

这会将状态设置为

{
  body: {
    first_name,
    last_name,
    email,
    phone,
    deliveryAddress
  }
}

您应使用this.setState(body)this.setState({ ...body })来获得以下状态:

{
  first_name,
  last_name,
  email,
  phone,
  deliveryAddress
}

通过toast之后将.then()放在axios.put()上的方式