reactjs - 重新渲染仅发生在第二次状态更改时,
问题描述
我希望你们能帮助我,我想我可能错过了一个简单的概念。我有一个组件,其中有另一个组件有一个从其父组件钻取的数组。在 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;
解决方案
推荐阅读
- javascript - 尝试使用 context.application.createDocument 编辑创建的文档时出错
- facebook - Facebook Marketing API 广告集过滤
- javascript - 避免内联 onClick 功能的最佳解决方案是什么?
- mysql - 根据多列选择第二个表中不存在的行
- webpack - Webpack 4 编译的 `.mjs` 依赖导致 `ReferenceError: module is not defined`
- bash - 有没有办法改进从 Windows 上的 Ubuntu 上的 Bash 复制到剪贴板格式?
- jhipster - 在 JHipster 中:创建后如何更改数据库设置?
- grafana - Grafana 5.1.0 中的divideSeriesList
- python - 通过所有记录相同来过滤分组的熊猫数据框
- java - 如何从java中的页面获取不同的url?