reactjs - 我想立即处理 setState
解决方案
这是我对您问题的解决方案
import React, { useState, useEffect } from "react";
const games = [
{ id: 1, genre: ["indie", "action"] },
{ id: 2, genre: ["indie"] },
{ id: 3, genre: ["action"] }
];
function ButtonComponent(props) {
const { genre, fn } = props;
return <button onClick={() => fn(genre)}>Click</button>;
}
function TestPage() {
const [genre, setGenre] = useState({ indie: 0, action: 0 });
const addGenrecount = (genres) => {
setGenre((previousState) => {
let { indie, action } = previousState;
genres.forEach((genre) => {
if (genre === "indie") indie = indie + 1;
if (genre === "action") action = action + 1;
});
return { indie, action };
});
};
useEffect(() => console.log("genre", genre), [genre]); // Logs to the console when genre change
return games.map((game) => {
const { id, genre } = game;
return <ButtonComponent key={id} genre={genre} fn={addGenrecount} />;
});
}
export default TestPage;
你也可以去codesandbox测试demo
https://codesandbox.io/s/xenodochial-dirac-q01h4?file=/src/App.js:0-968
只是友情提示:
如果您需要有关反应的帮助,我建议您将代码上传到代码沙箱,以便我们轻松重现或解决问题
推荐阅读
- .net - 如何:使用 Vb.Net 隐藏和显示 Tap 页面
- javascript - 如何在节点 js 中使用 xlsx/sheetjs 包在现有 xlsx 文件中创建新工作表?
- kotlin - 如何在使用带有 mapstruct 和不可变 kotlin 对象的构造函数实例化时进行部分更新
- r - 合并数据集并为 r 中其他数据集的缺失数据添加 0 行
- c++ - OOP 文件读取问题
- python - 在python中使用带有group by的条件滚动计数
- sql - AWS Athena 自定义数据格式?
- android - rs 文件中的 RenderScript 复制 3D 分配
- r - R dplyr:使用 dplyr 将列从字符转换为整数的问题
- c - 打印一个数字,然后将其擦除并在其位置打印另一个数字