【问题标题】:React function is not definedReact 函数未定义
【发布时间】:2024-05-16 18:00:02
【问题描述】:

我正在尝试使用从 Google API 导入的数据创建一个反应组件。我可以看到代码在 console.log 中运行,但是当我尝试在 React 渲染方法中使用该代码时,我什么也没得到。当我在类中移动我的函数时,它会作为未定义的函数出现。我不明白为什么?

function handleTouchTap() {
  console.log('CHIP selected');
  authorize();
}

function handleAccounts(response) {
  console.log(response.result.username);
  var username = response.result.username
  console.log(username);
}

function authorize(event) {
  var useImmidiate = event ? false : true;
  var authData = {
    client_id: CLIENT_ID,
    scope: SCOPES,
    immidiate: useImmidiate
  };
  gapi.auth.authorize(authData, function (response) {
    gapi.client.load('analytics', 'v3').then(function () {
      console.log(response);
      gapi.client.analytics.management.accounts.list().then(handleAccounts);
    });
  });
}

class Chips extends React.Component {
  render() {
    return (
      <div style={styles.wrapper}>
        <Chip
          onTouchTap={handleTouchTap}
          style={styles.chip} >
          <Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />
          Login
        </Chip>
        <Chip
          style={styles.chip} >
          <Avatar icon={<FontIcon className="material-icons">account_circle</FontIcon>} />
          {this.username}
        </Chip>
      </div>  
    );
  }
}

【问题讨论】:

  • 对不起。我不习惯 *。我试图发布我的代码,但花了一些时间来了解如何去做?
  • 我没有看到onTouchTap={handleTouchTap} 中引用的handleTouchTap 函数
  • 你能添加你得到的错误吗?
  • 我上面的代码没有任何错误。我在控制台中有用户名,但我想在芯片@{this.username} 中显示用户名。它没有显示任何用户名。非常抱歉,由于我没有足够的声望点,我无法附上屏幕截图向您展示控制台。

标签: function reactjs class google-analytics components


【解决方案1】:

在大多数情况下,当您想要渲染可能会更改的内容时,您希望将其添加到状态中。这样,当您调用 setState 时,组件就知道它需要重新渲染并显示更改。

这里我将函数添加为组件方法,以便您可以在结果上调用this.setState。理想情况下,您可能会使用 redux 并使用操作来执行此操作,但这将作为一个自包含组件工作。

class Chips extends React.Component {
  handleTouchTap = () => {
    console.log('CHIP selected');
    this.authorize();
  }

  handleAccounts = (response) => {
    var username = response.result.username;
    this.setState({
      username
    });
  }

  authorize = (event) => {
    var useImmidiate = event ? false : true;
    var authData = {
      client_id: CLIENT_ID,
      scope: SCOPES,
      immidiate: useImmidiate
    };
    gapi.auth.authorize(authData, (response) => {
      gapi.client.load('analytics', 'v3').then(() => {
        console.log(response);
        gapi.client.analytics.management.accounts.list()
          .then(this.handleAccounts);
      });
    });
  }

  render() {
    return (
      <div style={styles.wrapper}>
        <Chip
          onTouchTap={this.handleTouchTap}
          style={styles.chip}>
          <Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />
          Login
        </Chip>
        <Chip
          style={styles.chip} >
          <Avatar icon={<FontIcon className="material-icons">account_circle</FontIcon>} />
          {this.state.username}
        </Chip>
      </div>  
    );
  }
}

【讨论】: