在我组件的渲染函数中,我有:

render() {
    const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
      return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
    });
    return (
      <div>
        ...
                <ul>
                  {items}
                </ul>
         ...
      </div>
    );
  }

一切呈现良好,但当点击<li>元素时,我收到以下错误:

Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, dispatchMarker, nativeEvent, target, currentTarget, type, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Welcome.

如果我改成this。onitemclick。绑定(this, item) to (e) => onItemClick(e, item)内的映射函数,一切都按预期工作。

如果有人能解释我做错了什么,为什么我会得到这个错误,那就太好了

更新1: onItemClick函数如下所示。setState会导致错误消失。

onItemClick(e, item) {
    this.setState({
      lang: item,
    });
}

但是我不能删除这一行,因为我需要更新这个组件的状态


当前回答

我有这个错误,原来是我无意中包括一个对象在我的JSX代码,我本以为是一个字符串值:

return (
    <BreadcrumbItem href={routeString}>
        {breadcrumbElement}
    </BreadcrumbItem>
)

breadcrumbElement过去是一个字符串,但由于重构而变成了一个对象。不幸的是,React的错误消息并没有很好地将我指向存在问题的行。我必须一直跟踪堆栈跟踪,直到我识别出传递到组件中的“道具”,然后我找到了有问题的代码。

您需要引用对象的字符串值属性,或者将对象转换为所需的字符串表示形式。一个选项可能是JSON。stringify如果你真的想看到对象的内容。

其他回答

多亏了zerkms的评论,我才注意到我的愚蠢错误:

我有onItemClick(e,项目)当我应该有onItemClick(项目,e)。

如果出于某种原因你导入了firebase。然后尝试运行npm i—save firebase@5.0.3。这是因为firebase破坏反应本机,所以运行这个将修复它。

我的问题是,在render()函数的return语句中,不必要地在一个包含HTML元素的变量周围加上花括号。这使得React将其视为对象而不是元素。

render() {
  let element = (
    <div className="some-class">
      <span>Some text</span>
    </div>
  );

  return (
    {element}
  )
}

一旦我从元素中移除花括号,错误就消失了,元素被正确呈现。

试试这个

 {items && items.title ? items.title : 'No item'}

通常这是因为你没有正确地解构。以下面的代码为例:

const Button = text => <button>{text}</button>

const SomeForm = () => (
  <Button text="Save" />
)

我们用= text =>参数声明它。但实际上,React希望这是一个包揽一切的props对象。

所以我们真的应该这样做:

const Button = props => <button>{props.text}</button>

const SomeForm = () => (
  <Button text="Save" />
)

注意到区别了吗?这里的props参数可以被命名为任何东西(props只是与命名法相匹配的惯例),React只是期望一个具有键和val的对象。

使用对象解构,你可以这样做,也经常会看到这样的东西:

const Button = ({ text }) => <button>{text}</button>

const SomeForm = () => (
  <Button text="Save" />
)

...这工作。

有可能,任何偶然发现这一点的人只是不小心声明了他们组件的props参数而没有解构。