Reactjs 我想马上处理setState

Reactjs 我想马上处理setState,reactjs,setstate,Reactjs,Setstate,我想在点击按钮的同时计算独立和动作。然而,唯一真正的应用是行动。请告诉我怎么做。这是我解决你问题的办法 import React, { useState, useEffect } from "react"; const games = [ { id: 1, genre: ["indie", "action"] }, { id: 2, genre: ["indie"] }, { id: 3, genre:

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

这是我解决你问题的办法

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来测试演示

只是友好的提示:

如果您需要有关react的帮助,我建议您将代码上载到codesandbox,以便我们可以轻松复制或解决问题

欢迎使用so!请看