【问题标题】:Data from API rendering as empty (array/object issue)来自 API 的数据呈现为空(数组/对象问题)
【发布时间】:2019-06-10 08:36:42
【问题描述】:

我有一个旨在显示来自 API 的数据的组件:

class Item extends Component {
constructor(props) {
  super(props);
  this.state = {
    output: []
  }
}

componentDidMount() {
    fetch('http://localhost:3005/products/157963')
      .then(response => response.json())
      .then(data => this.setState({ output: data }));
  }


render() {
    console.log(this.state.output);
  return (
    <ItemPanel>
    <ItemBox>
    <BoxTitle>{this.state.output}</BoxTitle>
  </ItemPanel>
  );
  }
 export default Item;

console.log(this.state.output) 返回正确的数据,而我的组件不会呈现,它会抛出这个错误:

Objects are not valid as a React child (found: object with keys {id, general, brand, images}). If you meant to render a collection of children, use an array instead.

我猜来自 api 的数据是一个对象。我已经尝试过使用 JSON.parse 或 toString() :/

这是控制台的输出:

【问题讨论】:

  • 你能分享一下this.state.output 它的控制台吗?您到底想在id, general, brand, images 中的&lt;BoxTitle&gt; 中显示什么?
  • 让我们尝试在这里展示品牌,console.log 在上面

标签: javascript reactjs api


【解决方案1】:

您似乎在&lt;BoxTitle&gt; 中显示整个对象,让我们尝试在此处显示品牌。我已经更新了有问题的代码。 将初始状态 output [] 更新为 {}

class Item extends Component {
constructor(props) {
  super(props);
  this.state = {
    output: {}
  }
}

componentDidMount() {
    fetch('http://localhost:3005/products/157963')
      .then(response => response.json())
      .then(data => this.setState({ output: data }));
  }


render() {
    console.log(this.state.output);
  const { brand = {name : ""} } = this.state.output // added default name until we get actual value
  return (
    <ItemPanel>
    <ItemBox>
    <BoxTitle>{brand.name}</BoxTitle>
  </ItemPanel>
  );
  }
 export default Item;

【讨论】:

  • 这里需要小修复:{ brand = {name = ""} } -> { brand= {name: ""} },它现在正在工作。非常感谢!
  • &lt;ItemBox&gt;没有关闭应该是&lt;ItemBox/&gt;
  • 我现在正在努力从该 api 访问图像,已尝试 const { images = {primary:""} } = this.state.output;和一些变化,但仍然无法加载图像 src。帮助表示赞赏
  • 试试这个,const { brand = {name : ""} , images: {primary: {...}} = this.state.output
【解决方案2】:

当您的组件从您的 API 中获取数据时,它会渲染渲染函数中描述的元素树。

output 的初始状态是一个空数组,这是一个好的开始。

您应该考虑在从 API 加载数据或网络请求失败时向应用程序用户显示什么内容。

我很确定您不想按原样呈现成功调用 API 时返回的对象。

也就是说,JSON.stringify 函数可用于查看在成功调用 API 时设置的状态结果,然后再选择要显示的字段、显示方式和位置。

【讨论】:

    【解决方案3】:

    你可以更好地使用条件渲染,

    render() {
        console.log(this.state.output);
      return (
        <ItemPanel>
         <ItemBox>
         {
           if(this.state.output.brand.name !=== null) ?
             <BoxTitle>{this.state.output.brand.name}</BoxTitle> :
           <BoxTitle>Brand Name is Empty</BoxTitle>
         }
        </ItemPanel>
      );
      }
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      相关资源
      最近更新 更多