【问题标题】:Why is async await very slow?为什么异步等待非常慢?
【发布时间】:2022-01-17 14:10:10
【问题描述】:

我想为用户制作选择器来选择部门名称,并根据他选择的内容,在另一个选择器中查看部门类型,然后当他选择部门类型时,将学生显示在一个表格中。 我编写代码并获取数据,但因为我使用 (async..await),所以项目变得非常缓慢然后关闭。 怎么了?

function Teacher() {
  const [data1, setData1] = useState([]);
  const [data2, setData2] = useState([]);
  const [data3, setData3] = useState([]);
  const [SectionName, setSectionName] = useState('بستان');
  const [Type, setType] = useState('أ');

  useEffect(() => {
    async function getName() {
      await Axios
        .get(`http://localhost:3003/getSectionsName`)
        .then(result => setData1(result.data));
    }
    getName()
  }, []);

  const nameSelector = (
    <select className="custom-select" onChange={(e) => {
      const selectedSectionName = e.target.value;
      setSectionName(selectedSectionName);
    }}>
      {data1.map((item) =>
        <option key={item.id} value={item.SectionName}>
          {item.SectionName}
        </option>
      )}
    </select>
  )

  async function typeSelector() {
    await Axios.put(`http://localhost:3003/getSectionTypes`, { SectionName: SectionName }).then(result => setData2(result.data))
  }

  const typeSelect = (
    typeSelector(),
    <select className="custom-select" onChange={(e) => {
      const selectedSectionType = e.target.value;
      setType(selectedSectionType);
    }}>
      {data2.map((item) =>
        <option key={item.id}>
          {item.Type}
        </option>
      )}
    </select>
  )

  function student() {
    Axios.put(`http://localhost:3003/getStudents`, { Type: Type, SectionName: SectionName }).then(result => setData3(result.data))
  }

  const studentTable = (
    student(),
    <table className="table" >
      <thead className="thead-dark">
        <tr>
          <th scope="col">الطلاب</th>
        </tr>
      </thead>
      <tbody>
        {data3.map(item => {
          return <tr key={item.Id}>
            <td>{item.FullName}</td>
          </tr>
        })}
      </tbody>
    </table>
  )
  return (
    <div className="container p-2">
      <h4> اختر الصف </h4>
        {nameSelector}
      <br />
      <h4> اختر الشعبة </h4>
        {typeSelect}
      <br /><br />
      <h4>
        {studentTable}
      </h4>
    </div>
  )
}

export default Teacher;

【问题讨论】:

    标签: mysql node.js reactjs


    【解决方案1】:
      async function typeSelector() {
        await Axios.put(`http://localhost:3003/getSectionTypes`, { SectionName: SectionName }).then(result => setData2(result.data))
      }
    
      const typeSelect = (
        typeSelector(),
        ...
    

    完全错误 - 这意味着您使用逗号排序运算符调用 typeSelector() 作为渲染组件的副作用,并且可能最终进入无限渲染循环。非异步 typeSelector() 函数也会发生这种情况。

    您需要将这些 fetch 调用包装在合适的 useEffect() 挂钩中,可能是这样(我冒昧地将组件也提取到组件中。)

    function StudentTable({ students }) {
      return (
        <table className="table">
          <thead className="thead-dark">
            <tr>
              <th scope="col">الطلاب</th>
            </tr>
          </thead>
          <tbody>
            {students.map((item) => {
              return (
                <tr key={item.Id}>
                  <td>{item.FullName}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      );
    }
    
    function NameSelector({ sections }) {
      return (
        <select
          className="custom-select"
          onChange={(e) => setSectionName(e.target.value)}
        >
          {sections.map((item) => (
            <option key={item.id} value={item.SectionName}>
              {item.SectionName}
            </option>
          ))}
        </select>
      );
    }
    
    function TypeSelect({ types }) {
      return (
        <select
          className="custom-select"
          onChange={(e) => setType(e.target.value)}
        >
          {types.map((item) => (
            <option key={item.id} value={item.id}>
              {item.Type}
            </option>
          ))}
        </select>
      );
    }
    
    function Teacher() {
      const [sections, setSections] = useState([]);
      const [types, setTypes] = useState([]);
      const [students, setStudents] = useState([]);
      const [sectionName, setSectionName] = useState("بستان");
      const [type, setType] = useState("أ");
    
      // Load sections on mount
      useEffect(() => {
        Axios.get(
          `http://localhost:3003/getSectionsName`,
        ).then((result) => setSections(result.data));
      }, []);
      // Load types based on selected section
      useEffect(() => {
        Axios.put(`http://localhost:3003/getSectionTypes`, {
          SectionName: sectionName,
        }).then((result) => setTypes(result.data));
      }, [sectionName]);
      // Load students based on section and type
      useEffect(() => {
        Axios.put(`http://localhost:3003/getStudents`, {
          Type: type,
          SectionName: sectionName,
        }).then((result) => setStudents(result.data));
      }, [sectionName, type]);
    
      return (
        <div className="container p-2">
          <h4> اختر الصف </h4>
          <NameSelector sections={sections} />
          <br />
          <h4> اختر الشعبة </h4>
          <TypeSelect types={types} />
          <br />
          <br />
          <h4>
            <StudentTable students={students} />
          </h4>
        </div>
      );
    }
    
    export default Teacher;
    

    【讨论】:

    • 非常感谢,成功了。 ^_^
    • 但是有一点小错误,当我选择节名和类型时,他显示学生,但选择器中的单词返回为第一个值。
    【解决方案2】:

    尝试 useEffect() 具有依赖关系sectionName。当它发生变化时,您将调用typeSelector()student()

      const [data1, setData1] = useState([]);
      const [data2, setData2] = useState([]);
      const [data3, setData3] = useState([]);
      const [sectionName, setSectionName] = useState('بستان');
    
      const getName = async () => {
        const data = await Axios.get(`http://localhost:3003/getSectionsName`);
        setData1(data);
      };
    
      const typeSelector = async () => {
        const data = await Axios.put(`http://localhost:3003/getSectionTypes`, {
          SectionName: SectionName
        });
        setData2(data);
      };
    
      const student = async () => {
        const data = Axios.put(`http://localhost:3003/getStudents`, {
          Type: Type,
          SectionName: SectionName
        });
        setData3(data);
      };
    
      useEffect(() => {
        getName();
      }, []);
    
      useEffect(() => {
        typeSelector();
        student();
      }, [sectionName]);
    

    【讨论】:

      猜你喜欢
      • 2013-03-17
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多