使用React.createElement创建多个元素的警告

时间:2017-12-28 10:48:57

标签: reactjs react-redux

我使用React.createElement创建具有动态视图的元素:

{list && list.length !== 0 ?
    list.map((model, i) =>
        React.createElement(ListRow, {
            key: i,
            model,
            ...rowProps,

            onEdit: () => this.onEdit(model),
            onDelete: () => this.onDelete(model)
    })) : null
}

这对我来说很好,但是我在控制台中收到了这个警告:

Warning: Each child in an array or iterator should have a unique "key" prop. See *here shold be link* for more information.
    in EditableList (created by Connect(EditableList))
    in Connect(EditableList) (created by CreateInvoiceFormView)

即使list.length === 0<并且不知道为什么会这样。 我试图生成id,但没有帮助。

以下是整个组件代码:

class EditableList extends Component {
componentWillMount() {
    const {name, dispatch} = this.props;
    dispatch(createList(name));
}

componentWillUnmount() {
    const {name, dispatch} = this.props;
    dispatch(destroyList(name));
}

onAdd(item) {
    const {dispatch, name} = this.props;
    dispatch(openPopup(name, item));
}

onEdit(item) {
    const {dispatch, name} = this.props;
    dispatch(editItem(name, item));
    dispatch(openPopup(name, item));
}

onDelete(item) {
    const {dispatch, name} = this.props;
    dispatch(deleteItem(name, item));
}

render() {
    const {ListRow, list, rowProps, title} = this.props;

    return [
        <SectionTitleView title={title} add onClick={() => this.onAdd()}/>,
        <div>{list && list.length !== 0 ? list.map((model, i) =>
            React.createElement(ListRow, {
                key: i,
                model,
                ...rowProps,

                onEdit: () => this.onEdit(model),
                onDelete: () => this.onDelete(model)
            })) : null
        }
        </div>];
}
}

我在堆栈上搜索了这个问题,因为它无法解决任何类似问题,我不知道我做错了什么。如果我没有提供足够的信息来解决这个问题,请告诉我。

1 个答案:

答案 0 :(得分:1)

您正在使用react v16.0的最新语法,它要求您为所有元素添加键。由于您的SectionTitleView元素没有key属性,因此您收到此错误。

有关详细信息,请参阅: https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings

或者,您也可以将组件包装在渲染函数中的<div>内。