【问题标题】:React: Display element of array by idReact:按 id 显示数组的元素
【发布时间】:2018-01-18 03:39:56
【问题描述】:

我正在尝试显示我的 items 数组中的一个元素。我可以将元素记录到控制台...但无法渲染。在我的setState 中,我制作了 itemDetail,它从 items 数组中获取第一个元素:(也许有更好的方法来做到这一点?)

this.setState({ items: items, itemDetail: items[0], value: this.state.value })

当我尝试拨打 {itemDetail} 时,它给了我错误:

“对象作为 React 子对象无效(找到:带有键 {id, name} 的对象)....”

下面的完整代码。如何在 React 中渲染数组中的第一个元素?或者更好的是,按 ID 显示元素。谢谢。

constructor(props){
    super(props);
    this.state = {
      items: []
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  componentDidMount(){
    const items = [
      {
        'id': 0,
        'name': 'firstName'
      },
      {
        'id': 1,
        'name': 'secondName'
      }
    ];

    this.setState({ items: items, itemDetail: items[0] });
  }


  render(){

    const { items, itemDetail } = this.state;

    console.log(itemDetail);

    return(
      <div className="container">
        {itemDetail}
      </div>
    );
  }

【问题讨论】:

    标签: javascript arrays reactjs object element


    【解决方案1】:

    React 不知道如何渲染对象 itemDetail。让我们帮助他:

    render(){
    
        const { items, itemDetail } = this.state;
    
        console.log(itemDetail);
    
        return(
            <div className="container">
                <div className="item-id">{itemDetail.id}</div>
                <div className="item-name">{itemDetail.name}</div>
            </div>
        );
    }
    

    希望这会有用。

    【讨论】:

    • 这很有用。谢谢你的回答!
    【解决方案2】:

    您的状态必须如下所示,因为您在 render() 中访问 itemDetails

    this.state = {
        items: [],
        itemDetail: {} 
    }
    

    【讨论】:

    • 啊,我错过了这个。谢谢!
    【解决方案3】:
    const itemsArray = this.state.items
    return(
          <div className="container">
            {itemsArray && itemsArray[0]}
          </div>
    

    如果你是根据一些道具或状态值来决定,你可以做类似的事情

    const itemsArray = this.state.items
    const slectedIndex = this.state.selectedIndex or this.props.selectedIndex//depends how you are getting selectedindex logic
    return(
          <div className="container">
            {itemsArray && itemsArray[slectedIndex]}
          </div>
    

    【讨论】:

    • 感谢您的回答!我能够应用类似的逻辑来解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2021-12-25
    • 2021-10-10
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多