javascript - React json 获取值

标签 javascript arrays json reactjs

我是 React 新手,并开始考虑拉入 json 数据。 为了测试我正在使用:https://randomuser.me/api/?results=5

我想要实现的是,当我单击 json 中的用户名时,它将控制台记录用户名。如何将值从 json 传递到控制台日志?

const API = 'https://randomuser.me/api/?results=5';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      logins: [],
    };
  }

  componentDidMount() {
    fetch(API)
      .then(response => response.json())
      .then(data => {
        let logins = data.results.map((uname) => {
          return (
            <div>
              <button>{uname.login.username}</button>
            </div>
          )
        })
        this.setState({logins: logins});
      })
  }

  render() {
    return (
      <div>
        {this.state.logins}
      </div>
    );
  }
}

在 componentDidMount 中返回 html 代码是个好主意还是应该让它继续渲染?

最佳答案

您可以做您喜欢做的事情,但通常您会将组件创建(它不是真正的 HTML)留给渲染:

const API = 'https://randomuser.me/api/?results=5';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      logins: [],
    };
  }

  componentDidMount() {
    fetch(API)
      .then(response => response.json())
      .then(data => {
        this.setState({logins: data.results});
      })
  }

  render() {
    return (
      <div>
        {this.state.logins.map((uname) => (
            <div>
              <button>{uname.login.username}</button>
            </div>
        ))}
      </div>
    );
  }
}

state 通常应保存数据,并将该数据的渲染留给render

<小时/>

旁注:您的 fetch 调用缺少两件事:

  1. 检查ok状态,以及

  2. 错误处理程序

    fetch(API)
      .then(response => {                             // ***
        if (!response.ok) {                           // ***
          throw new Error({status: response.status}); // ***
        }                                             // ***
      })                                              // ***
      .then(response => response.json())
      .then(data => {
        // ...
      })
      .catch(err => {                                 // ***
        // Handle the error                           // ***
      });                                             // ***
    

fetch 不会拒绝 404 等状态错误。

关于javascript - React json 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024611/

相关文章:

javascript - 如果内容未保存,则防止导航到另一个 View

javascript - 如果失败,则使用if/else Javascript语句禁用过渡动画

javascript - 如何在同步模式下获取 outputStream block ?

android - 如何获取 JsonReader 字节来计算百分比

json - 如何读取并解析json文件并将其添加到shell脚本变量中?

javascript - 单击按钮而不刷新整个页面

arrays - D 编程语言字符数组

javascript - JavaScript 中的哈希数组

java - Android/Java 将文本文件中的名称存储在 String 数组中,并将整数存储在 int 数组中

javascript - 在Javascript中将数组设置为json格式的值