首页 > 解决方案 > 在 React 组件中如何绑定对象值?

问题描述

我是 React Js 的新手。我必须使用 React Js 开发一个小型应用程序。我从 api 调用中获取数据并将值绑定到组件中。尝试一些代码但出现错误。

带有键 {HeaderModel} 的对象)。如果您打算渲染一组子项,请改用数组。

{
  "HeaderModel":
        {
        "DataModel": null,
        "HeaderLogo": "test.jpg",
         "HeaderLink1": AboutUS,
        "HeaderLink2": ContactUS,
        "HeaderLink3": Register,
        "LoginButtonText": "LOGIN",
        "LoginButtonTextLink": "http://sample.com",
        "ContactLogo": "fa fa-question-circle"
      }   
}

下面的代码参考 React JS 文件。

import React, { Component } from "react";
import "../Assests/css/main.css";
import data from "../Constants/SampleJson/TestJson.json";

class Header extends Component {
  constructor() {
    super();
  }

  state = {
    values: null,
  };

  render() {
    return (
      <div className="main-header">
        <p>{this.state.values}</p> // Getting Error
        <div class="container">
          <div className="header-sticky">
            <div class="logo-wrap">
              <a href="/" target="_self">
                {/* <img src={require({items.HeaderLogo})} /> */}
              </a>
              <h1>{this.state.values.HeaderModel.HeaderLogo}</h1> //// Getting Error while biniding
            </div>
          </div>
        </div>
      </div>
    );
  }

  componentDidMount() {
    fetch("http://loalhost:55423/api/TestAPIController/GetPageData")
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            values: result,
          });
          console.log(test);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error,
          });
        }
      );
  }
}

export default Header;

API响应如下

{
    "HeaderModel":
        {
            "DataModel":null,
            "HeaderLogo":"sample.jpg",
            "HeaderLink1":"contactus",
            "HeaderLink2":"aboutus",
            "HeaderLink3":"register",
            "LoginButtonText":"LOGIN",
            "LoginButtonTextLink":"http://sample.com",
            "ContactLogo":"fa fa-question-circle"
       }
}

标签: reactjs

解决方案


您遇到的错误很容易解决。

第一个与获取数据后的对象有关<p>{this.state.values}</p>this.state.valuesReact 不支持显示对象,因此您会得到尝试其他东西的建议。为了修复它,要么完全删除此标签,要么将其更改为<p>{JSON.stringify(this.state.values)}</p>使其显示为漂亮的字符串。

第二个问题是在<h1>{this.state.values.HeaderModel.HeaderLogo}</h1> this.state.values获取完成之前 in 为空。为了修复它,你不应该h1在状态改变之前渲染这个标签。这可以通过有条件地与&&操作员一起显示来解决

这是修改后的代码:

import React, { Component } from "react";
import "../Assests/css/main.css";
import data from "../Constants/SampleJson/TestJson.json";

class Header extends Component {
  constructor() {
    super();
  }

  state = {
    values: null,
  };

  render() {
    return (
      <div className="main-header">
        <p>{JSON.stringify(this.state.values)}</p> // Getting Error
        <div class="container">
          <div className="header-sticky">
            <div class="logo-wrap">
              <a href="/" target="_self">
                {/* <img src={require({items.HeaderLogo})} /> */}
              </a>
              {this.state.values && <h1>{this.state.values.HeaderModel.HeaderLogo}</h1>} 
            </div>
          </div>
        </div>
      </div>
    );
  }

  componentDidMount() {
    fetch("http://loalhost:55423/api/TestAPIController/GetPageData")
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            values: result,
          });
          console.log(test);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error,
          });
        }
      );
  }
}

export default Header;

推荐阅读