【问题标题】:How to make new axios request when onChange is triggered?触发 onChange 时如何发出新的 axios 请求?
【发布时间】: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


【解决方案1】:

你应该添加dropdownValue作为依赖,只在数据变化时触发请求,而不是像click/onchange这样的事件:

const [people, setPeople] = useState([]);
const [dropdownValue, setDropdownValue] = useState('All');
const fetchData = async () {
    const req = await axios.get("/All");
    setPeople(req.data);
}
const handleChange = (e) {
    setDropdownValue(e.target.value)
}
useEffect(() => {
    fetchData();
}, [dropdownValue]);

【讨论】:

  • 这是正确的答案,使用一点本地状态,然后在 useEffect 中监听它,Sonny 你应该在你的 useEffect 中使用await fetchData()
  • 我试过了,效果很好。你太棒了!
  • @Akshat 很高兴听到这个消息,如果有帮助,请接受它作为答案,因为它可以帮助其他人解决类似问题
【解决方案2】:

useEffect 使您能够在组件被渲染或道具或状态发生变化时运行某些东西。将其包含在单击时调用的函数中使其无用。 useEffect 应该调用其他函数,但绝不应该从函数内部调用。

【讨论】:

  • adjunct: useEffect 是一个记忆钩子,换句话说,它不是由触发事件调用的回调,而是由它的依赖项触发的副作用。它与 React 类中的 componentDidMountcomponentDidUpdatecomponentWillUnmount 具有相同的目的,但统一为一个 API。默认情况下,React 在每次渲染后运行效果
  • 好的。我知道了。谢谢
猜你喜欢
  • 2021-06-07
  • 2017-08-06
  • 2021-06-30
  • 1970-01-01
  • 2022-11-02
  • 2021-07-12
  • 2019-02-05
  • 2019-01-27
  • 2020-11-07
相关资源
最近更新 更多