繁体   English   中英

在 React Hooks 中。 如何将 state 设置为随机数并使用它来显示数组中的字符串

[英]In React Hooks. How to set state to a random number and use that to display a string from an array

嗨,我正在上一门学习 React Hooks 的课程,但我被困在一项任务上。 我的任务是创建一个按钮,onClick 显示来自该数组的随机报价。

const App = (props) => {
  const [selected, setSelected] = useState(0)

  return (
    <div>
      {props.anecdotes[selected]}
    </div>
  )
}

const anecdotes = [
  'If it hurts, do it more often',
  'Adding manpower to a late software project makes it later!',
  'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
  'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
  'Premature optimization is the root of all evil.',
  'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
]

ReactDOM.render(
  <App anecdotes={anecdotes} />,
  document.getElementById('root')
)

我试图自己解决这个问题,但是我遇到了错误。 想知道是否有人对此有一个简单的解释? 谢谢

这是我不断收到的错误。

TypeError:无法读取未定义 App src/App.js:14 11 的属性“0” 12 | 返回 ( 13 |

14 | 随机获取 | ^ 15 | {轶事[选定]} 16 | 17 | )

从数组中选择随机值的钩子的解决方案

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Example(props) {

  const [count, setCount] = useState(0);

  const { anecdotes } = props;
  return (
    <div>
      <p>You clicked and random value from array: <h4>{count}</h4></p>
      <button onClick={() => setCount(anecdotes[Math.floor(Math.random()*anecdotes.length)])}>
        Click me
      </button>
    </div>
  );
}
ReactDOM.render(
  <Example  anecdotes={[1,4,3,2,8,5]}/>,
  document.getElementById('root')
);

从数组中选择随机值的钩子

因此,您的 App 组件会收到报价,显示当前的报价,并根据您想要的新报价。

您唯一需要做的就是添加一个按钮,通过setSelected更改selected值,如下所示; https://codesandbox.io/s/hungry-dream-4b3eg

useState 钩子为您提供 2 个 arguments,第一个是read您的 state,第二个是write您的 state。

我不会剧透一切,因为你正在上课:) 所以让数字随机化,也许用其他方法,你就会有你预期的行为。

const App = props => {
  const [selected, setSelected] = useState(0);

  return (
    <div>
      <button onClick={() => setSelected(4)}>change quote</button> // <=== this addition
      {props.anecdotes[selected]}
    </div>
  );
};

您所需要做的就是生成一个介于 0 和长度 -1 之间的 anectodes 数组的随机数。

const App = ({anecdotes}) => {
  const [selected, setSelected] = useState(0)

  const handleClick = () => {
      const randomNumber = Math.floor(Math.random() * anecdotes.length);
      setSelected(randomNumber);
  }

  return (
    <div>
      <button onClick={handleClick} >Get Random</button>
      {anecdotes[selected]}
    </div>
  )
}

https://codesandbox.io/s/blissful-hofstadter-mr01k

随机分量:

import React, {  useState } from "react";

import "./styles.css";

const anecdotes = [
  'If it hurts, do it more often',
  'Adding manpower to a late software project makes it later!',
  'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
  'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
  'Premature optimization is the root of all evil.',
  'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
]

export default function showRandom() {
  const [selected, setSelected]=useState(0);
  return (
    <div className="App">
    <h1> {anecdotes[selected]}</h1>
     <button onClick={()=>setSelected(Math.floor(Math.random() * `anecdotes.length))}>Show Random </button>`
      </div>
  );
}

应用组件:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import Random from "./showRandom";
function App() {
  return (
    <div className="App">
     <Random /></div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM