如何重新渲染 .map() 列表

当我单击将数组的第一个元素发送到最后一个位置的按钮时,我尝试重新渲染列表,但是,当我单击该按钮时,组件不会重新渲染,即使 console.log 显示该数组已更改: codesandbox

import React, { useState } from "react";


const DailySchedule = () => {

  const [exerciseList, setExerciseList] = useState([

    "exercise 1",

    "exercise 2",

    "exercise 3"

  ]);


  return (

    <div>

      <section>

        <h2>Warm-up</h2>


        <ul>

          {exerciseList.map((exrcs, idx) => {

            return (

              <li>

                {exrcs}{" "}

                {idx === 0 && (

                  <button

                    onClick={() => {

                      exerciseList.push(exerciseList.shift());

                      setExerciseList(exerciseList);

                      console.log(exerciseList);

                    }}

                  >

                    Done

                  </button>

                )}

              </li>

            );

          })}

        </ul>

      </section>

    </div>

  );

};


export default DailySchedule;


芜湖不芜
浏览 156回答 4
4回答

慕侠2389804

此问题是因为数组引用未更改。&nbsp; onClick={() => {&nbsp; &nbsp; const list = [...exerciseList]&nbsp; &nbsp; list.push(list.shift());&nbsp; &nbsp; setExerciseList(list);&nbsp; }}

动漫人物

这是因为您正在exerciseList直接修改数组,但您不应该这样做,因为状态更新将看到列表是相同的并且不会触发重新渲染。相反,制作数组的副本,然后使用setExerciseList:const newList = [...exerciseList]newList.push(newList.shift())setExerciseList(newList)

慕丝7291255

这是因为 state 中的数组引用没有改变。像这样更新 setState 调用,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exerciseList.push(exerciseList.shift());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setExerciseList([...exerciseList]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(exerciseList);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Done&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </button>

慕勒3428872

您必须更改数组引用以反映状态中的情况。setExerciseList([...exerciseList]);工作代码 -&nbsp;https://codesandbox.io/s/react-playground-forked-ohl1u
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript