如何从一个函数获取初始状态并调用另一个将状态作为参数传递的函数?

时间:2019-09-11 16:57:30

标签: reactjs

我试图尽可能地概括我的问题,因此以下代码只是一个包含我实际问题主要概念的示例。 我需要从一个函数获取初始状态,更新所有状态,然后调用另一个函数,其中输入参数是更新后的状态。

在我的实际问题中,我需要从AWS Cognito调用一个函数(Auth.currentAuthenticatedUser())以更新用户名信息并设置初始状态。根据我的阅读,将其放置在componentDidMount中可能是适当的,以防止产生副作用。 以下代码具有2个功能,第一个功能称为“ changeState”,它为“ gui_amuchastegui”设置用户名状态。第二个功能验证第一个功能中是否设置了状态,并根据答案设置了密码。

import React, { Component } from "react";

class App extends Component {
  constructor() {
    super();
    this.state = {
      username: "",
      password: ""
    };
  }

  componentDidMount() {
    console.log("componentDidMount");
    this.changeState();
    this.changeStateRelational();
  }

  changeState() {
    console.log("called function!");
    this.setState({ username: "gui_amuchastegui" });
  }

  changeStateRelational() {
    let apple = this.state.username;
    if (apple == "gui_amuchastegui") {
      console.log("It works!");
      this.setState({ password: "1234" });
    } else {
      console.log("Did not work");
    }
  }

  render() {
    return (
      <div className="App">
        <h1>Hello World!</h1>
        <h3>Username state is: {this.state.username}</h3>
        <h3>Password is: {this.state.password}</h3>
      </div>
    );
  }
}

export default App;

在线检查我的代码-> https://codesandbox.io/s/nice-banach-61cs4

我希望第一个函数为“ gui_amuchastegui”设置“用户名”,第二个函数将在状态更新后立即调用。之后,调用第二个函数时,我希望将“ password”的状态设置为“ 1234”,并能够在页面上呈现该状态。

0 个答案:

没有答案