正确使用 useState 变量

Nat*_*lie 0 javascript reactjs react-hooks

我正在尝试将id带有 useState的道具应用于我的 DrumPad 组件,从其父 App 组件传入。在我的 app.js 文件中,正如它当前设置的那样,我收到一个错误“'id' 被分配了一个值但从未使用过。” 假设我需要使用 useState 设置变量以将 id 传递给 DrumPad 组件,我需要更改什么才能正确应用它?

应用程序.js:

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

const App = () => {
  const id = useState(''); // (Don't have setId since it won't change)

  return (
    <div className="App">
      {sounds.map(sound => (
        <DrumPad
          id={sounds.id}
        />
      ))}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

DrumPad.js:

const DrumPad = () => {
  return (
    <div id="id">

    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

更新:

我发现它在不使用 useState 设置状态的情况下工作正常,所以我是这样做的(但不确定它是否最佳):

const App = () => {

  return (
    <div className="App">
      {sounds.map(sound => (
        <DrumPad
          id={sound.id}
        />
      ))}
    </div>
  );
}


const DrumPad = (props) => {

  return (
    <div id={props.id}>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ash 5

您误用了useState,并引用了错误的变量,也没有真正使用id代码中的状态。

请参考JSX 中的Destructuring assignment , useState, Props

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

const App = () => {

// useState returns an array (Tuple), you may use id[0] for the initial value
// const id = useState('');


//     v In case you don't want to use setId - 
// Thats how the "Destructuring assignment" works
const [id] = useState('');


  return (
    <div className="App">
      {sounds.map(sound => (
        <DrumPad
            id={sound.id}

//              v You referenced the global `sounds` variable which is an array
//          id={sounds.id}
        />
      ))}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

此外,您应该使用 props 来引用您传递的属性:

const DrumPad = (props) => {
  const { id } = props;
  return <div id={id}/>
}
Run Code Online (Sandbox Code Playgroud)