useEffect不适用于语义UI React中的多个下拉列表

问题描述 投票:0回答:1

我正在使用语义UI React。以下JS代码对我不起作用:

import React, { useState, useEffect } from "react";
import { Dropdown, Form, Button } from "semantic-ui-react";

export const MovieDropdown = () => {
  const [movie, setMovie] = useState("");
  const [person, setPerson] = useState("");
  const [movieOptions, setMovieOptions] = useState([]);
  const [personOptions, setPersonOptions] = useState([]);

  useEffect(() => {
    Promise.all([
      fetch("/people").then(res =>
        res.json()
      ),
      fetch("/movies").then(res =>
        res.json()
      )
    ])
      .then(([res1, res2]) => {
        console.log(res1, res2);
        var make_dd = (rec) => {
            rec.map(x => {
              return {'key': x.name, 'text': x.name, 'value': x.name}
            })
        }
        setPersonOptions(make_dd(res1))
        setMovieOptions(make_dd(res2))

      })
      .catch(err => {
        console.log(err);
      });
  });

  return (
    <Form>
      <Form.Field>
        <Dropdown
          placeholder="Select Movie"
          search
          selection
          options={movieOptions}
          onChange={(e, {value}) => setMovie(value)}
        />
      </Form.Field>
      <Form.Field>
        <Dropdown
          placeholder="Select Person"
          search
          selection
          options={personOptions}
          onChange={(e, {value}) => setPerson(value)}
        />
      </Form.Field>

    </Form>
  );
};
export default MovieDropdown;

问题是运行此组件时我失去了数据库连接。我尝试使用MySQL和SQLite,它给出了相同的问题。如何解决呢?每个组件应获取1个抓取信息吗?我先谢谢你。

亲切的问候,Theo

javascript reactjs semantic-ui-react
1个回答
0
投票

嗯,我不知道数据库连接,但是在useEffect中调用api的推荐方法如下:

useEffect({
 // your code here only once
},[])

OR,

useEffect({
 // your code here will run whenever id changes
},[id])

您的useEffect将在每个渲染器上运行,不建议使用此时间/方式进行api调用。

© www.soinside.com 2019 - 2024. All rights reserved.