【问题标题】:how to work with json in react.js如何在 react.js 中使用 json
【发布时间】:2017-10-21 21:39:30
【问题描述】:

这里是 json 格式的数据:https://jsonplaceholder.typicode.com/posts

这是我的代码。运行它后,我在 console.log 中出现错误:“对象作为 React 子项无效(找到:带有键 {userId、id、title、body} 的对象)。如果您打算渲染一组子项”。 为什么当我在 COMpoonentDidMount 中使用 console.log(response) 时,我有我的对象数组但不能在 render() {} 中使用它。我做错了什么?

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

  componentDidMount() {  
      var component = this;
      api.fetchInfo() 
        .then(function(response) {
            component.setState( { users: response } );
        });
  }

  render() { 
    //console.log('here' + this.state.users);
    return (
      <ul>

        <p>{this.state.users}</p>
        {
            this.state.users.map(
                function(elem) {
                   return <li>{elem.userId}</li> 
                }
            )
        }
      </ul>
    )
  }
}


ReactDOM.render(
  <App />,
  document.getElementById('app')
);

【问题讨论】:

    标签: javascript json reactjs jsx


    【解决方案1】:

    这行jsx:

    <p>{this.state.users}</p>
    

    要求 React 渲染一个普通的对象。它不知道如何为您做到这一点。如果你想让json打印到页面上,可以stringify它:

    <p>{JSON.stringify(this.state.users)}</p>
    

    否则,您可能希望通过 map 并呈现对您有意义的标记。

    【讨论】:

    • 我不知道怎么打。我反应的第三天,它对我来说仍然很奇怪:)
    【解决方案2】:

    问题是由线路引起的

    <p>{this.state.users}</p>
    

    您可以删除它或使用:

    <p>{JSON.stringify(this.state.users)}</p>
    

    简单来说,解释是这样的:

    • 在任何 jsx 块中,您可以将 javascript 嵌入花括号中,即{}
    • {} 块内的 javascript 的结果必须是:字符串、null 或另一个有效的 jsx 对象。如果是其他问题,您将看到您看到的错误。

    在你的情况下,你也有一个有效的块:

        {
            this.state.users.map(
                function(elem) {
                   return <li>{elem.userId}</li> 
                }
            )
        }
    

    上面的块返回有效的 jsx,它是一堆 &lt;li&gt; 元素。那些&lt;li&gt; 元素本身有一个{elem.userId},可以直接解释为字符串。

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多