You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React调用API获取数据控制台打印正常但页面展示值不更新如何解决

问题原因

你在state中定义的存储公钥的字段是value,但在render方法中尝试解构读取不存在的pubkey字段,因此页面始终无法渲染获取到的公钥值。

修复方案

有两种可选修复方式,任选其一即可:

  • 方法1:修改render方法中的字段读取逻辑,直接读取state中的value字段
    将原有代码中
    const { pubkey } = this.state;
    
    修改为
    const { value: pubkey } = this.state;
    
  • 方法2:统一状态字段名更符合语义,将state初始化和setState操作中的value改为pubkey
    1. 构造函数中的state初始化修改为:
    this.state = {
      pubkey: null
    };
    
    1. setState部分修改为:
    this.setState({ pubkey: pubkey });
    

修复后完整代码

import React, { Component } from "react";
import { Button } from "@material-ui/core";
import { Image } from "react-bootstrap";
import albedo from "@albedo-link/intent/lib/albedo.intent";
import albedologo from "./albedo.png";

class LogInWithAlbedo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pubkey: null
    };
  }
  Albedo() {
    albedo.publicKey({}).then((res) => {
      const { intent, pubkey, signature, signed_message } = res;
      console.log({ intent, pubkey, signature, signed_message });
      this.setState({ pubkey });
    });
  }
  render() {
    const { pubkey } = this.state;
    return (
      <div>
        <div>
          <Button
            style={{ width: "207px", height: "40px" }}
            variant="contained"
            color="default"
            onClick={this.Albedo.bind(this)}
          >
            Login With <Image style={{ width: "55px" }} src={albedologo} />
          </Button>
          <h2>It is {pubkey}.</h2>
        </div>
      </div>
    );
  }
}

export default LogInWithAlbedo;

内容的提问来源于stack exchange,提问作者BlackBadPinguin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:39:03