首页 > 解决方案 > 重新渲染仅发生在第二次状态更改时,

问题描述

我希望你们能帮助我,我想我可能错过了一个简单的概念。我有一个组件,其中有另一个组件有一个从其父组件钻取的数组。在 Child 组件中,列表随后被映射并显示。

现在的问题是当我更新数组的状态时,即使用 SetArray([...array, newItem]) 将另一个项目添加到数组中,

ChildComponent 中的 useEffect 将 console.log 新数组,但实际显示不会改变,直到我向数组中添加另一个元素。

当我添加另一个元素时,我添加的第一个元素会出现,但第二个元素不会出现。

希望这有点道理

子组件:

import React, { useState, useEffect } from "react";
////EDITOR//// List

import { Grid, Button, Card } from "@material-ui/core";
import Timestamp from "./Timestamp";

const TimestampList = ({ setTime, match, setMatchEdit, render }) => {
  const [timestamps, setTimestamps] = useState([]);

  useEffect(() => {
    const setInit = async () => {
      try {
        console.log(match);
        const m = await match.scores.map(player => {
          console.log(player);
          if (player.totalScores) {
            return player.totalScores;
          }
        });
        console.log(m);
        if (m[0] && m[1]) {
          setTimestamps(
            [...m[0], ...m[1]].sort((a, b) => {
              return a.time - b.time;
            })
          );
        }

        if (m[0] && !m[1]) {
          setTimestamps(
            m[0].sort((a, b) => {
              return a.time - b.time;
            })
          );
        }

        if (m[1] && !m[0]) {
          setTimestamps(
            m[1].sort((a, b) => {
              return a.time - b.time;
            })
          );
        }
      } catch (error) {
        console.log(error);
      }
    };
    if (match) {
      setInit();
    }
    console.log(match);
  }, [match]);

  return (
    <Grid
      component={Card}
      style={{ width: "100%", maxHeight: "360px", overflow: "scroll" }}
    >
      {timestamps && timestamps.map(timestamp => {
        console.log(timestamp);
        const min = Math.floor(timestamp.time / 60);
        const sec = timestamp.time - min * 60;
        const times = `${min}m ${sec}sec`;
        return (
          <Timestamp
          
            time={times}
            pointsScored={timestamp.points}
          
          />
        );
      })}
      <Grid container direction='row'></Grid>
    </Grid>
  );
};

export default TimestampList;

标签: reactjs

解决方案


推荐阅读