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

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是这样的:

...
{
  ...
  <Foo />
  ...
}
...

我需要注释掉它来调试一些东西。我在IDE中使用键盘快捷键,结果是这样的:

...
{
  ...
  { /* <Foo /> */ }
  ...
}
...

当然,这是无效的——对象作为react子对象是无效的!

其他回答

try{
    throw new Error(<p>An error occured</p>)
}catch(e){
    return (e)
}

上面的代码产生了错误,然后我重写了它,像这样:

try{
    throw(<p>An error occured</p>)
}catch(e){
    return (e)
}

注意try块中new Error()的删除…

为了避免这个错误消息,编写代码的一个更好的方法是将一个字符串传递给throw new error()而不是JSX,并在catch块中返回JSX,就像这样:

try{
    throw new Error("An error occurred")
}catch(e){
    return (
        <p>{e.message}</p>
    )
}

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

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参数而没有解构。

我得到这个错误每当我在我的FlatList的renderItem函数上调用async。

在调用FlatList中的状态数据之前,我必须创建一个新函数来将我的Firestore集合设置为我的状态。

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

我花了半天时间来解决这个问题

我想根据用户是否登录显示一个数组

这就是我的代码 返回({userLogged ?userLoggedCart: cartItems} .map((item)=>{返回//无关代码})) 但这是错误的,如果你的代码是这样的,你就得把它改成

if (userLogged){return (userLoggedCart.map((item)=>{return //您的代码})}否则{cartItems.map((item)=>{return //您的代码})}