首页 > 解决方案 > 我想立即处理 setState

问题描述

在此处输入图像描述

单击按钮时,我想同时计算“独立”和“动作”。然而,唯一真正的应用是“动作”。请告诉我怎么做。

标签: reactjssetstate

解决方案


这是我对您问题的解决方案

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


只是友情提示:

如果您需要有关反应的帮助,我建议您将代码上传到代码沙箱,以便我们轻松重现或解决问题


推荐阅读