[英]Passing new Array instead of array literal to useState shows empty array
[英]useState define an empty array with new Array method
我正在从商店获取数据,它是一组对象。 在 useState 中,我想设置一个 data.length 大小的数组,最初都设置为 false。 但是,当我设置该值时,它会为我设置的每个 state 变量返回一个空数组 []。 我还尝试在useeffect中更新state,但没有任何效果。 我无法弄清楚这里有什么问题。
function Datatable() {
let data = useSelector((state) => state.dish);
console.log(data.length)
const [clicked1, setClicked1] = useState(new Array(data.length).fill(false));
const [clicked2, setClicked2] = useState(new Array(data.length).fill(false));
const [clicked3, setClicked3] = useState(new Array(data.length).fill(false));
const dispatch = useDispatch();
function setAllStates() {
setClicked1(new Array(data.length).fill(false));
setClicked2(new Array(data.length).fill(false));
setClicked3(new Array(data.length).fill(false));
}
useEffect(() => {
setAllStates();
}, []);
控制台数据的图像这是我创建表的 jsx
<TableBody>
{data.map((row, index) => (
<TableRow
key={row.id}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
>
<TableCell component="th" scope="row">
<img width={150} height={100} src={row.image} />
</TableCell>
<TableCell align="right">{row.dishName}</TableCell>
<TableCell align="right">
{clicked1[index] == false ? (
<>
<Button
onClick={() => handleOnclick("Rank 1", index, row)}
>
Rank 1
</Button>
</>
) : (
<Typography>Selected</Typography>
)}
</TableCell>
这是控制台数据中表格的图像。长度显示 0 两次,然后显示 30。我在其父组件的减速器中填充数据。 但是所有的 arrays 仍然是未定义的。 在表格中,我在数据表中显示的所有内容都是未定义的。 (注意:我正在创建一个长度为 data.length.data.image 的表,data.description 仅在表中显示,仅在 clicked1[index] == false 时才显示的按钮未定义。
除非data.length
为 0,否则这必须工作。
function Datatable() {
const data = useSelector((state) => state.dish);
const [clicked1, setClicked1] = useState();
const [clicked2, setClicked2] = useState();
const [clicked3, setClicked3] = useState();
const dispatch = useDispatch();
function setAllStates(size) {
const newArray = new Array(size).fill(false);
setClicked1(newArray);
setClicked2(newArray);
setClicked3(newArray);
}
useEffect(() => {
if(data) setAllStates(data.length);
}, [data]);
}
你的代码看起来不错。
可能的错误可能是 -> data.length 为 0。
在设置data
后检查添加console.log(data.length)
。
现在代码:
let data = useSelector((state) => state.dish);
console.log(data.length) // if this is zero , this is causing empty array
const [clicked1, setClicked1] = useState(new Array(data.length).fill(false));
...
编辑:
添加data
作为依赖项。
useEffect(() => {
setAllStates();
}, [data]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.