首页 > 解决方案 > 对象作为 React 子对象无效(找到:带有键 {..} 的对象)。.....改用数组。在 Select(由 Context.Consumer 创建)

问题描述

这是我的数据(clientsResponse)的样子:

[{"id":1,"description":"CORPORATE","en":"Corprorate","gr":"Εταιρία","type":"ASSET"},{"id":2,"description":null,"en":"Property","gr":"Περιουσίας","type":"ASSET"}]

我有以下代码片段:

//populate data
      fetchAllLos() {
        let that = this;
        this.props.losStore.getAllLos().then(function (clientsResponse) {
          that.setState({ data: [clientsResponse] })
        }).catch(function (error) {
          console.log(error.message);
        });

      }
.....
render(){
.......
             <FormItem>{getFieldDecorator('antd',
                { initialValue: "PROPERTY" },
                { }] })(<Select
                  showSearch style={{ width: 200 }} 
                  onChange={this.handleChangeLineOfBusiness}>
                  {this.state.data.filter((los)=> los.type !=="ASSET" &&
                          <Option key={los.id} value={los.id}>{los.id}</Option>)}

                </Select>)}
              </FormItem>
.....

在浏览器上导致以下错误:

Error: Objects are not valid as a React child (found: object with keys {id, description, en, gr, type}). If you meant to render a collection of children, use an array instead.
    in Select (created by Context.Consumer)

我究竟做错了什么?

标签: javascriptreactjs

解决方案


替换你的this.state.data.filter-

this.state.data.filter(los => los.type !== 'ASSET').map(option => (
    <Option key={option.id} value={option.id}>{option.id}</Option>
));

另外,由于clientResponse已经是一个数组,所以请这样做-

this.setState({data: clientResponse})

推荐阅读