React调用API获取数据控制台打印正常但页面展示值不更新如何解决
问题原因
你在state中定义的存储公钥的字段是value,但在render方法中尝试解构读取不存在的pubkey字段,因此页面始终无法渲染获取到的公钥值。
修复方案
有两种可选修复方式,任选其一即可:
- 方法1:修改
render方法中的字段读取逻辑,直接读取state中的value字段
将原有代码中
修改为const { pubkey } = this.state;const { value: pubkey } = this.state; - 方法2:统一状态字段名更符合语义,将
state初始化和setState操作中的value改为pubkey- 构造函数中的state初始化修改为:
this.state = { pubkey: null };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
相关产品推荐
相关产品推荐

