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

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,
    });
}

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


当前回答

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

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

其他回答

在使用Firebase的情况下,如果把它放在import语句的末尾不能工作,那么你可以尝试把它放在一个生命周期方法中,也就是说,你可以把它放在componentWillMount()中。

componentWillMount() {
    const firebase = require('firebase');
    firebase.initializeApp({
        //Credentials
    });
}
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>
    )
}

这是我的代码:

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      value: null,
      getDatacall : null
    }
    this.getData = this.getData.bind(this)
  }
  getData() {
  //   if (this.state.getDatacall === false) {
    sleep(4000)
    returnData("what is the time").then(value => this.setState({value, getDatacall:true}))
    // }
  }
  componentDidMount() {
    sleep(4000)

    this.getData()
  }
  render() {
    this.getData()
    sleep(4000)
    console.log(this.state.value)
    return (
      <p> { this.state.value } </p>
    )
  }
}

我就遇到了这个错误。我不得不把它改成

 render() {
    this.getData()
    sleep(4000)
    console.log(this.state.value)
    return (
      <p> { JSON.stringify(this.state.value) } </p>
    )
  }

希望这能帮助到一些人!

我的问题非常特别:在我的.env文件中,我在有我的api url的行中放了一个注释:

API_URL=https://6ec1259f.ngrok.io #comment

当我尝试登录/注册时,我会得到不变违反错误,因为api url是错误的。

我只是让自己经历了一个非常愚蠢的错误版本,我不妨在这里为后代分享一下。

我有一些JSX是这样的:

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

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

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

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