【发布时间】:2022-01-04 11:46:01
【问题描述】:
我正在尝试根据下拉菜单显示数据。 When selection changes I am invoking onChange which gathers the new backend link(I am using axios for that).我知道 useEffect 不能在 JS 函数中工作(不要介意注释的代码正在工作),但是我怎样才能实现这一点,以便当我的选择发生变化时,会发出一个新的 axios 请求,该请求将基于收集数据选择的值。
import React, {useEffect, useState} from 'react';
// import axios from "axios";
import axios from "./axios";
import Table from './Table';
function Data() {
const[people,setPeople]= useState([]);
// useEffect(() =>{
// async function fetchData() {
// const req = await axios.get("/All");
// setPeople(req.data);
// }
// fetchData();
// }, []);
// console.log(people);
function handleChange(e){
return (
useEffect(() =>{
async function fetchData() {
const req = await axios.get(e.target.value);
setPeople(req.data);
}
fetchData();
},[])
);
}
return (
<div>
<div>
<form action="/action_page.php">
<label for="cars">Manufacturer:</label>
<select name="cars" id="cars" onChange={handleChange}>
<option selected value="All" >All</option>
<option value="Apple" >Apple</option>
<option value="OnePLus" >One Plus</option>
<option value="Samsung" >Samsung</option>
<option value="Google" >Google</option>
<option value="Sony" >Sony</option>
<option value="Huawei" >Huawei</option>
</select>
</form>
</div>
<Table data={people}/>
</div>
)
}
export default Data
这是后端代码:
import express from "express";
import bodyParser from "body-parser";
import mysql from "mysql";
import Cors from "cors";
const app=express();
const port= process.env.PORT || 8001;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());
app.use(Cors());
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "MySQL@05",
database: "interview"
});
app.get("/", (req, res)=> {
res.send("Hello World!!");
});
app.get("/All", (req,res)=> {
const abc = "select * from products";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.get("/Apple", (req,res)=> {
const abc = "select * from products WHERE manufacturer='Apple'";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.get("/Samsung", (req,res)=> {
const abc = "select * from products WHERE manufacturer='Samsung'";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.get("/OnePlus", (req,res)=> {
const abc = "select * from products WHERE manufacturer='One Plus'";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.get("/Google", (req,res)=> {
const abc = "select * from products WHERE manufacturer='Google'";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.get("/Huawei", (req,res)=> {
const abc = "select * from products WHERE manufacturer='Huawei'";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.get("/Sony", (req,res)=> {
const abc = "select * from products WHERE manufacturer='Sony'";
db.query(abc, (err,result)=> {
res.send(result);
});
});
app.listen(port, ()=> {
console.log("Listening on port");
});
【问题讨论】:
-
不要将 useEffect 放在事件函数中。完成后调用 axios 函数并更新状态。 useEffect 对于在组件渲染时获取状态很有用。
标签: javascript node.js reactjs axios