使用 onclick 渲染对象数组中的数据

rendering data from an array of objects using an onclick

我正在尝试使用 React 构建一个 Flashcard 应用程序以帮助保留编程概念。但是,我 运行 在构建组件时遇到了麻烦。我有一个名为 Definition 的组件,我想通过以下方式显示从数据数组中提取的概念的随机 definition/explanation:App 呈现 FlashCard,FlashCard 呈现 Definition。

我在 App 组件上添加了一个带有 onClick 的按钮来执行此操作。但是,每当我单击该按钮时,都会收到一条错误消息,指出数据未定义。我做错了什么?

export const conceptArray = [
    { term: 'Redux', definition: 'A predictable state container for Javascript apps. This makes it easier to manage state' },
    { term: 'thunk', definition: 'A subroutine used to inject an additional calculation into another subroutine, primarily used to delay a calculation until result is needed' },
    { term: 'context API', definition: 'Provides a way to pass and store data down a React component tree without writing it into every level of the component hierarchy. It does so by leveraging Provider and Consumer components' },
    { term: 'reducer pattern', definition: 'A pure function that takes in previous state and action and returns next state' },
    { term: 'prop drilling', definition: 'Passing down props from upper level to lower level components in the component tree, where components in between have no use for these props' },
    { term: 'props', definition: 'Data or information passed to child components from parents' },
    { term: 'state', definition: 'Data being managed within a Component'},
  ];
// data and components
import { conceptArray } from "./data";
import FlashCard from "./components/FlashCard";

function App() {
  const [randomDef, setRandomDef] = useState('a bunch of shit I don\'t understand');

  // this should store the individual concept (individual items in the concept Array)
  const getCard = () => {setRandomDef(conceptArray[Math.floor(Math.random) * conceptArray.length].definition)};

  console.log(randomDef);
  console.log(conceptArray);
  console.log(conceptArray.length);
  console.log(conceptArray[0].definition);
  console.log(conceptArray[0].term);

  return (
    <div className="App">
      <header className="App-header">
        <FlashCard randomDef={randomDef} />
        <button onClick={getCard}>Get FlashCard</button>
      </header>
    </div>
  );
}

export default App;
// components
import Definition from "./Definition";

const FlashCard = props => {
    return (
        <div>
            <Definition randomDef={props.randomDef} />
        </div>
    )
}

export default FlashCard;
import React from "react";

const Definition = props => {
    return (
        <div>
            <p>{props.randomDef}</p>
        </div>
    )
}

export default Definition;

首先 Math.random 是一个函数 - 你必须调用它。其次 - 你应该将 Math.random 的结果乘以数组长度 - 否则它将始终等于 0.

conceptArray[Math.floor(Math.random() * conceptArray.length)]