javascript 如何在单击按钮时使用状态列出结果

pcww981p  于 2023-11-15  发布在  Java
关注(0)|答案(2)|浏览(81)

我试图编写一个组件,当单击查找按钮时列出一组结果。然而,当我单击查找按钮时,当我调用setResults([])时,results状态变量没有被重置。
它也不返回结果数组中的每个结果,只返回最新的一个。我是否也错误地调用了results.mapresult.resultItems.map
这是我点击查找按钮三次后的样子:


的数据
我需要它看起来像这样,即使再次单击“查找”按钮:


const SearchContact = () => {
    const [results, setResults] = useState([]);

    const handleFind = () => {
      setResults([]);

      const response = [
        { name: "Tim", email: "[email protected]" },
        { name: "Fred", email: "[email protected]" }
      ];

      for (var i = 0; i < response.length; i++) {
        const resultItems = [];

        resultItems.push(<div>{response[i].name}</div>);
        resultItems.push(<div>{response[i].email}</div>);

        setResults([...results, { resultItems: resultItems }]);
      }
    }

    return (
      <Button onClick={handleFind}>Find</Button>
        {results.map((result, index) => {
          return (
            <div key={index}>
              {result.resultItems.map((resultItem, index) => {
                return <div key={index}>{resultItem}</div>;
              })}
            </div>
          );
      })}
    )
}

字符串

ubbxdtey

ubbxdtey1#

试试tihs:

const SearchContact = () => {
  const [results, setResults] = useState([]);

  const handleFind = () => {
    const response = [
      { name: "Tim", email: "[email protected]" },
      { name: "Fred", email: "[email protected]" }
    ];

    const newResults = response.map((item) => {
      const resultItems = [
        <div key="name">{item.name}</div>,
        <div key="email">{item.email}</div>
      ];

      return { resultItems };
    });

    setResults(newResults);
  };

  return (
    <div>
      <Button onClick={handleFind}>Find</Button>
      {results.map((result, index) => (
        <div key={index}>
          {result.resultItems.map((resultItem, idx) => (
            <div key={idx}>{resultItem}</div>
          ))}
        </div>
      ))}
    </div>
  );
};

字符串

1hdlvixo

1hdlvixo2#

只需在XNUMX Find函数中调用setResults(results),无需调用setResults([])或任何循环逻辑,如下所示:

const handleFind = () => {

      // probably change to an API call in future
      const response = [
        { name: "Tim", email: "[email protected]" },
        { name: "Fred", email: "[email protected]" }
      ];
      setResults(response);
      }
    }

字符串
而在JSX中:

{results.map((result, index) => {
          return (
            <div key={index}>
              <div>{result.name}</div>
              <div>{result.email}</div>
            </div>
          );
      })}

相关问题