admin管理员组

文章数量:1425707

I'm working on the freeCodeCamp drum machine app. In my app with function arrow ponents, I set state of display with the useState hook in the parent ponent and pass it as a prop to the child ponent. In the parent ponent, I try to render the display state in a div. However, when the method is triggered (on click of the "drum pad" div), the app crashes. In the console I get an error that says "Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {display}). If you meant to render a collection of children, use an array instead." I've been following along a YouTube tutorial for this project but using arrow function ponents and Hooks instead of regular classes as used in the tutorial--in the tutorial (around 1:55 of this video) the person successfully does what I'm trying to do, so I think the issue is something to do with using Hooks or arrow function ponents.

// APP COMPONENT (PARENT)

const sounds = [
  { id: 'snare', letter: 'Q', src: '.mp3' },
  // etc.
];

const App = () => {

  const [display, setDisplay] = useState(''); // <----

  const handleDisplay = display => { // <----
    setDisplay({ display });
  }

  return (
    <div className="App">
      <div className="drum-machine">
        <div className="display">
          <p>{display}</p> // <---- Related to error in console
        </div>
        <div className="drum-pads">
          {sounds.map(sound => (
            <DrumPad
              id={sound.id}
              letter={sound.letter}
              src={sound.src}
              handleDisplay={handleDisplay} // <----
            />
          ))}
        </div>
      </div>
    </div>
  );
}

// DRUMPAD COMPONENT (CHILD)

const DrumPad = ({ id, letter, src, handleDisplay }) => {

  let audio = React.createRef();

  const handleClick = () => {
    audio.current.play();
    audio.current.currentTime = 0;
    handleDisplay(id); // <----
  }

  return (
    <div
      className="drum-pad"
      id={id}
      onClick={handleClick}
    >
      <p className="letter">{letter}</p>
      <audio
        ref={audio}
        id={letter}
        src={src}
      >
      </audio>
    </div>
  );
}

I'm working on the freeCodeCamp drum machine app. In my app with function arrow ponents, I set state of display with the useState hook in the parent ponent and pass it as a prop to the child ponent. In the parent ponent, I try to render the display state in a div. However, when the method is triggered (on click of the "drum pad" div), the app crashes. In the console I get an error that says "Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {display}). If you meant to render a collection of children, use an array instead." I've been following along a YouTube tutorial for this project but using arrow function ponents and Hooks instead of regular classes as used in the tutorial--in the tutorial (around 1:55 of this video) the person successfully does what I'm trying to do, so I think the issue is something to do with using Hooks or arrow function ponents.

// APP COMPONENT (PARENT)

const sounds = [
  { id: 'snare', letter: 'Q', src: 'https://www.myinstants./media/sounds/snare.mp3' },
  // etc.
];

const App = () => {

  const [display, setDisplay] = useState(''); // <----

  const handleDisplay = display => { // <----
    setDisplay({ display });
  }

  return (
    <div className="App">
      <div className="drum-machine">
        <div className="display">
          <p>{display}</p> // <---- Related to error in console
        </div>
        <div className="drum-pads">
          {sounds.map(sound => (
            <DrumPad
              id={sound.id}
              letter={sound.letter}
              src={sound.src}
              handleDisplay={handleDisplay} // <----
            />
          ))}
        </div>
      </div>
    </div>
  );
}

// DRUMPAD COMPONENT (CHILD)

const DrumPad = ({ id, letter, src, handleDisplay }) => {

  let audio = React.createRef();

  const handleClick = () => {
    audio.current.play();
    audio.current.currentTime = 0;
    handleDisplay(id); // <----
  }

  return (
    <div
      className="drum-pad"
      id={id}
      onClick={handleClick}
    >
      <p className="letter">{letter}</p>
      <audio
        ref={audio}
        id={letter}
        src={src}
      >
      </audio>
    </div>
  );
}
Share Improve this question edited Sep 24, 2019 at 21:21 nCardot asked Sep 24, 2019 at 20:52 nCardotnCardot 6,6238 gold badges56 silver badges100 bronze badges 2
  • 1 {JSON.stringify(display)} or make display value simply a string instead of an object. setDisplay(display) – Alexander Staroselsky Commented Sep 24, 2019 at 20:55
  • 1 setDisplay({ display }); is converting whatever the value display is to an object that looks like this: {"display": DISPLAYSTRING}. This happens due to a JS mechanic called Destructuring (developer.mozilla/en-US/docs/Web/JavaScript/Reference/…). As the previous ment mentions, using setDisplay(display) will make it work. – Jacob Penney Commented Sep 24, 2019 at 21:01
Add a ment  | 

2 Answers 2

Reset to default 4

You're setting the state as an object instead of a string. Remove the curly brackets around it.

const handleDisplay = display => {
  setDisplay(display);
}

This was already answered, but since you are following a tutorial, I am assuming you are learning React and wanted to point a couple of things to help you :)

The incorrect use of state was pointed out, but just for clarification (and the reason I think you were using an object): in the "old" way, with Class ponents, the state used to be an object, and you needed to update it like an object. This example here shows that. With Hooks, you don't need to set the whole State object, only that specific state property. More info here.

Another point is, in your CodePen example at least, you were missing the import for useState. You either need to import it like this import { useState } from React or use it like this React.useState, since this is a separate module, not imported by default when you import React.

The last point is, when creating ponents using a loop (like your <DrumPad> with the map) you need to provide a "key" attribute. that will help React keep track of things that needs to be updated or rerendered.

O updated your code with those changes in this link, if you wanna see it working:

https://codesandbox.io/s/reverent-browser-zkum2

Good luck and hope you are enjoying React Hooks :)

本文标签: javascriptReact HooksUncaught Invariant Violation Objects are not valid as a React childStack Overflow