useEffect 问题在获取数据时不起作用
useEffect problem don't work when fetching data
我使用 useEffect 在 React 功能组件中获取数据,它必须在 data (useState) 中获取数据
所以问题是页面加载正确 api res 没有问题。
function AdminDashBoard() {
const [data, setData] = useState([]);
const [selectedOption, setselectedOption] = useState("");
const [c_options, setc_options] = useState([]);
useEffect(() => {
axios.get("http://localhost:8000/products")
.then(response => { setData(response.data.result); })
.then(
() => {
data.forEach(element => {
let options = [];
if (options.indexOf(element.category) < 0) options += { value: element.category, label: element.category };
setc_options(options);
})
}
)
.catch(err => { console.log(err) })
}, [])
function handleSelectChange(event) {
setselectedOption(event.target.value);
console.log("selected category : ")
console.log(selectedOption)
}
return (
<div class="row-fluid main">
<div className="form-group">
<label for="formControlSelect2">select category :</label>
<Select class="form-control" id="formControlSelect2" onChange={() => handleSelectChange} options={c_options} />
</div>
<span id="products"></span>
</div>
);
}
export default AdminDashBoard;
write another useEffect and put data dependency in an array and clean up second then in your useEffect becaucse that is unnesseary
useEffect(() => {
const oldDtate=[...data]
oldDtate.forEach(element => {
let options = [];
if (options.indexOf(element.category) < 0) options += { value:
element.category, label: element.category };
setc_options(options)
}, [data])
我使用 useEffect 在 React 功能组件中获取数据,它必须在 data (useState) 中获取数据 所以问题是页面加载正确 api res 没有问题。
function AdminDashBoard() {
const [data, setData] = useState([]);
const [selectedOption, setselectedOption] = useState("");
const [c_options, setc_options] = useState([]);
useEffect(() => {
axios.get("http://localhost:8000/products")
.then(response => { setData(response.data.result); })
.then(
() => {
data.forEach(element => {
let options = [];
if (options.indexOf(element.category) < 0) options += { value: element.category, label: element.category };
setc_options(options);
})
}
)
.catch(err => { console.log(err) })
}, [])
function handleSelectChange(event) {
setselectedOption(event.target.value);
console.log("selected category : ")
console.log(selectedOption)
}
return (
<div class="row-fluid main">
<div className="form-group">
<label for="formControlSelect2">select category :</label>
<Select class="form-control" id="formControlSelect2" onChange={() => handleSelectChange} options={c_options} />
</div>
<span id="products"></span>
</div>
);
}
export default AdminDashBoard;
write another useEffect and put data dependency in an array and clean up second then in your useEffect becaucse that is unnesseary
useEffect(() => {
const oldDtate=[...data]
oldDtate.forEach(element => {
let options = [];
if (options.indexOf(element.category) < 0) options += { value:
element.category, label: element.category };
setc_options(options)
}, [data])