单击按钮显示数组中的随机字符串[反应]

时间:2020-04-02 00:31:19

标签: javascript reactjs react-hooks

我正在尝试构建一个显示随机问题的简单应用。我可以在挂载和页面刷新时成功显示数组中的随机字符串。

我想显示一个不同的按钮“ onClick”随机问题,而不是刷新页面?

到目前为止,这里的代码:

export const QuestionContainer = () => {
  const [response, setResponse] = useState({});

  useEffect(() => {
    fetchData().then(res => setResponse(res));
  }, []);

  const { records = [] } = response;

  const questions = records.map(record => record.fields.question);

  console.table(questions);

 // const randomNum = arr => {
 //   return Math.floor(Math.random() * arr.length);
 //  };

  return (
    <div className='questions-container'>
      <h1>{questions[0]}?</h1>
      <button onClick={() => console.log('more')}>More</button>
    </div>
  );
};

const questions是一个字符串数组示例-['hello','world','noob问题']

1 个答案:

答案 0 :(得分:1)

您非常亲密!只需使用onClick设置要显示的索引,就可以了!这应该起作用:

const randomIndex = (arr) => { // returns a random int value to use as an index
    return Math.floor(Math.random() * arr.length)
}
export const QuestionContainer = () => {
  const [response, setResponse] = useState({});
  const [index, setIndex] = useState(0) // 0 initially, as you had in your example

  useEffect(() => {
    fetchData().then(res => setResponse(res));
  }, []);

  const { records = [] } = response;

  const questions = records.map(record => record.fields.question);

  console.table(questions);

  return (
    <div className='questions-container'>
      <h1>{questions[index]}?</h1>
      <button onClick={_ => setIndex(randomIndex(questions)}>More</button>
    </div>
  );
};