prop更改时,React功能组件不会重新渲染

时间:2020-09-29 07:08:59

标签: javascript reactjs use-effect

我正在使用axios在useEffect中进行请求,而我传递的道具只是一个简单的ID。这是我的代码的主要部分;

    return (
        <>
            <Table striped bordered hover>

1 个答案:

答案 0 :(得分:2)

您忘了在依赖项数组中传递prop stationData

    const [stationData, setStationData] = useState([]);

    useEffect(() => {
        console.log(`Fetching station ${stationId}`)
        axios.get(`http://localhost:3001/stations/${stationId}`)
            .then(response => {
                console.log(response);
                setStationData(response.data);
            })
            .catch(error => {
                console.log(error);
            });
    }, [stationData]); <--- HERE

    return (
        <>
            <Table striped bordered hover>