我需要另一个组件中的useEffect (而不是直接连接到App.js的组件)。我如何重新制作并将其放入单独的文件中?它最好是定制钩子的自定义函数吗?这是App.js组件:
import React, {useState, useEffect} from 'react';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import axios from 'axios';
import Competitions from './components/Competitions';
import CompetitionForm from './components/CompetitionForm';
import Navigation from './components/Navigation';
import './styles/App.css'
const App = () => {
const [competitions, setCompetitions] = useState([]);
const [defaultCompetitionValue, setDefaultCompetitionValue] = useState({})
useEffect(() => {
axios.get('http://localhost:4000/app/getCompetitions')
.then(res => res.data)
.then(res => {
for(let i = 0; i < res.length; i++) {
competitions[i] = {
"value": res[i].name,
"label": res[i].name,
"id": res[i]._id
}
};
setCompetitions(competitions);
})
.then(() => setDefaultCompetitionValue({"value": competitions[0].value, "label": competitions[0].value}))
}, [competitions]);
if(competitions.length > 0 && defaultCompetitionValue) {
return (
<div className = "container">
<Router>
<div className = "sidebar">
<Navigation />
</div>
<div className = "content">
<Switch>
<Route exact path = "/homepage">
<Competitions
competitions = {competitions}
defaultCompetitionValue = {defaultCompetitionValue}
/>
</Route>
<Route exact path = "/CompetitionForm">
<CompetitionForm competitions = {competitions}/>
</Route>
</Switch>
</div>
</Router>
</div>
)
}
return (<></>)
};
export default App;我需要另一个组件中的useEffect (不是直接连接到App.js)。我如何重新制作并将其放入单独的文件中?它最好是定制钩子的自定义函数吗?
发布于 2021-10-07 16:26:10
useEffect是一个为功能组件提供反应的钩子。您可以在任何组件中使用它,从react导入,如下所示。您不需要从一个组件传递到另一个组件。
import { useEffect } from 'react';有关更多细节,您可以在钩子上阅读他们的官方文档。https://reactjs.org/docs/hooks-reference.html
https://stackoverflow.com/questions/69483933
复制相似问题