Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

javascript - How to display items in React using array.map, useState, useEffect at random with onClick?

I'm trying to make a name generator component that will display a name with its corresponding meaning from an array when the user clicks a button. I'm using useState to set the initial state as well as to cycle through the array randomly, as well as useEffect (although not sure if its necessary). I would prefer to use the array.map() method for randomizing. Component code below:

import React, { useState, useEffect } from "react";

const GeneratorNew = () => {
  const startingName = [{ id: 0, value: "Update Name!" }];

  const nameList = [
      { id: 1, name: 'Astghik', meaning: 'little star' }, 
      { id: 2, name: 'Tagouhi', meaning: 'Queen' }, 
      { id: 3, name: 'Lusine', meaning: 'Moon' }]
  ;

  const [stateOptions, setStateValues] = useState(startingName);
  // startingName.push(...nameList);

  useEffect(() => {
    setStateValues(nameList);
  }, []);

  return (
    <div>
      <h1>{nameList.name}</h1>
      <p>{nameList.meaning}</p>
      <button>
        {stateOptions.map((nameList, index) => (
          <option key={nameList.id}>{nameList.value}</option>
        ))}
      </button>
    </div>
  );
};

export default GeneratorNew;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import React, { useState, useEffect } from "react";

const GeneratorNew = () => {
  const startingName = [{ id: 0, value: "Update Name!" }];

  const nameList = [
      { id: 1, name: 'Astghik', meaning: 'little star' }, 
      { id: 2, name: 'Tagouhi', meaning: 'Queen' }, 
      { id: 3, name: 'Lusine', meaning: 'Moon' }]
  ;

  const [stateOptions, setStateValues] = useState(startingName);


  const handleOnClick = () => {
     setStateValues(nameList[Math.floor(Math.random() * (nameList.length - 1))])
  }

  return (
    <div>
      <h1>{nameList.name}</h1>
      <p>{nameList.meaning}</p>
      <button onClick={() => handleOnClick()}>
        {stateOptions.map((nameList, index) => (
          <option key={nameList.id}>{nameList.value}</option>
        ))}
      </button>
    </div>
  );
};

export default GeneratorNew;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...