问题
I am using Semantic UI React. The following JS code does not work for me:
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;
Problem is that I lose the DB connection when running this component. I tried with MySQL and SQLite and it gives the same issue. How to solve this? Should I have 1 fetch per component? I thank you in advance.
Kind regards, Theo
回答1:
Well, I dont know about the DB Connetion, but the remmended way of calling api in useEffect is like this:
useEffect({
// your code here only once
},[])
OR,
useEffect({
// your code here will run whenever id changes
},[id])
Your useEffect will run on every render,which is not recommended time/ way to make api calls.
来源:https://stackoverflow.com/questions/62288497/useeffect-not-working-with-multiple-dropdowns-in-semantic-ui-react