代码之家  ›  专栏  ›  技术社区  ›  Steverino

React状态将数组作为属性,但当传递时,它会嵌套到一个自命名对象中吗?

  •  0
  • Steverino  · 技术社区  · 6 年前

    我有一个反应状态,看起来是这样的:

      state = {
        itemList: []
      };
    

    我有一个如下所示的渲染函数:

      render() {
        return (
          <div className="App">
            <ListingContainer itemList={this.state.itemList} />
          </div>
        );
      };
    

    ListingContainer 组件如下所示:

    const ListingContainer = (itemList) => {
        return(
            <div>
                {
                    // getting type error, itemList.map is not a function
                    itemList.map(({data}) => <Item data={data} />)
                }
            </div>
        );
    };
    

    我的状态设置如下:

      componentWillMount() {
        // getList promise is confirmed to be providing an array
        this._asyncRequest = getList().then(
          itemList => {
            this._asyncRequest = null;
            // breakpoint confirms itemList is array at this time
            this.setState({itemList});
          }
        );
      }
    

    一个断点,位于 itemList.map 调用显示itemList实际上是一个包含我正在查找的实际itemList数组的对象,如下所示:

    itemList:
    {
      itemList: [ ... ]
    }
    

    itemList:
    [ ... ]
    

    为什么我的数组被转换成包含我的数组的自命名对象?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Sahil Raj Thapa    6 年前

    在React中,如果您将道具作为 <ListingContainer itemList={this.state.itemList} /> 可以在名为props的对象或任何您命名的对象中访问它。

    const ListingContainer = (itemList) => {...} 您已将该对象命名为 itemList . 这就是你得到结果的原因 itemList.itemList = [ ... ] .

    因此,您可以更改代码,也就是说,将解构用作 {itemList}

    const ListingContainer = ({itemList}) => {
        return(
            <div>
                {
                    // getting type error, itemList.map is not a function
                    itemList.map(({data}) => <Item data={data} />)
                }
            </div>
        );
    };
    

    或者不进行分解

    const ListingContainer = (props) => {
            return(
                <div>
                    {
                        props.itemList.map(({data}) => <Item data={data} />)
                    }
                </div>
            );
        };