[英]React How to re render map function on change of variabel?
Here is an excerpt which should show my problem.这是一段应该显示我的问题的摘录。 In my project I do something with the grid and now I want to reset it, but I dont know how it works because if I change the grid variable, the.map() function doesnt re render.在我的项目中,我对网格做了一些事情,现在我想重置它,但我不知道它是如何工作的,因为如果我更改网格变量,the.map() function 不会重新渲染。 I hope you understand my problem and you can help me.我希望你能理解我的问题,你可以帮助我。
export default function App() {
const getInitialGrid = () => {
const grid = [];
for (let row = 0; row < 20; row++) {
const currentRow = [];
for (let col = 0; col < 50; col++) {
currentRow.push([]);
}
grid.push(currentRow);
}
return grid;
};
const grid = getInitialGrid();
return (
<div className="App">
{grid.map(function (row, rowIdx) {
return (
<div className="grid-row" key={rowIdx}>
{row.map(function (node, colIdx) {
return <div className="node">hi</div>;
})}
</div>
);
})}
</div>
);
}
Its the same code like here.它与此处的代码相同。
Thanks a lot!非常感谢!
You should use useState hook for that.您应该为此使用useState挂钩。
import React, { useState } from 'react';
export default function App() {
// App code
const [grid, setGrid] = useState(getInitialGrid());
// more App code
then if you want to assign a new value to the grid and cause a rerender you do it like this (inside your App component):然后,如果您想为网格分配一个新值并导致重新渲染,您可以这样做(在您的 App 组件中):
setGrid(yourNewGrid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.