【问题标题】:Apply loading state to the items that are clicked in an array - React将加载状态应用于数组中单击的项目 - React
【发布时间】:2021-11-05 14:28:31
【问题描述】:

我正在尝试仅为单击的项目设置加载程序。目前,我面临的问题是,它将加载状态应用于数组中的所有项目。

我使用CodeSandbox 创建了一个工作示例。有人可以帮忙吗?

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const cars = [{ name: "Benz" }, { name: "Jeep" }, { name: "BMW" }];

  const handleClick = () => {
    // API Call
    dispatch({ type: "SET_LOADING", loading: true });
    // Loading stops once response is recieved.
  };
  return (
    <div className="App">
      {cars.map(({ name }) => (
        <button onClick={handleClick}>
          {state.loading ? "Loading..." : name}
        </button>
      ))}
    </div>
  );
}

【问题讨论】:

  • 您需要为这些按钮添加一些索引。如果您不打算更改它们的顺序,您可以简单地使用 .map 回调中的第二个参数 - 索引。然后保存在您的状态中,哪个 id 处于加载状态

标签: javascript reactjs


【解决方案1】:

您可以使用汽车名称作为加载属性,然后检查加载属性的值,而不是布尔值。我假设名称是唯一的,否则添加一个 id 属性并检查它。

import { useReducer } from "react";
import "./styles.css";

const initialState = {
  loading: false
};

const reducer = (state, action) => {
  switch (action.type) {
    case "SET_LOADING":
      return { ...state, loading: action.loading };
    default:
      return state;
  }
};

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const cars = [{ name: "Benz" }, { name: "Jeep" }, { name: "BMW" }];

  const handleClick = (e,name) => {
    // API Call
    dispatch({ type: "SET_LOADING", loading: name });
    // Loading stops once response is recieved.
    // Assing loading = '' once response is received
  };
  return (
    <div className="App">
      {cars.map(({ name }) => (
        <button onClick={(e)=>{handleClick(e,name)}}>
          {state.loading===name ? "Loading..." : name}
        </button>
      ))}
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多