运行 获取调用 onLoad - React
Run a fetch call onLoad - React
我是 React 新手。
我正在尝试 运行 在我的 React 页面加载时进行提取调用以获取一些数据。不过,我不确定我是否正确调用了该事件。
我是这样称呼它的:
export default function GetRecipe(props) {
let { name } = useParams()
const [searchQuery, setSearchQuery] = useState('')
const [recipeName, setRecipeName] = useState('')
const [methodStepsList, setMethodStepsList] = useState([])
const [ingredients, setIngredients] = useState([])
const retrieveRecipe = function (e) {
console.log('getting recipe')
e.preventDefault()
console.log(searchQuery.length)
let queryString
if (searchQuery.length) {
queryString = `http://localhost:3001/getbasicrecipe/?name=${searchQuery}`
} else {
queryString = `http://localhost:3001/getbasicrecipe/?name=${name}`
}
fetch(queryString, {
method: 'GET',
headers: { 'Content-type': 'application/json' },
})
.then((resp) => resp.json())
.then((json) => {
console.log(json)
let result = json
let recipeName = result[0].recipe_name
let recipeMethod = result[0].recipe_method.split(/\r?\n/)
console.log(recipeMethod)
setRecipeName(recipeName)
setMethodStepsList(recipeMethod)
setIngredients(json)
})
}
return (
<div>
<div className="recipe-form-container">
<form className="recipe-form">
[...]
</div>
</form>
</div>
</div>
)
我阅读了有关 componentDidMount()
的内容,但不知道如何将其包含在我的代码中。
谢谢!
如果您使用的是基于 Class 的组件
componentDidMount(){
//Your code here
}
render(){
return ...
}
如果使用函数组件
useEffet(()=>{
//your code here
}, [])
return (...)
这是使用useEffect
hook的经典案例-
与 return 函数使用之前一样 -
useEffect(()=>{ retrieveRecipe(); },[]);
代替componentDidMount
我建议在创建您自己的项目之前玩一下 react.js 教程以掌握它的窍门。
如果您使用的是 class 组件,那么,正如您提到的,您可以像这样使用 componentDidMount() 生命周期方法:
componentDidMount() {
// Runs after the first render() lifecycle
retrieveRecipe();
}
...
render(){
...
}
文档:https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
但是,如果您使用的是功能组件,则应改用 useEffect 钩子,如下所示:
useEffect(() => {
retrieveRecipe();
}, []); // by using an empty array as dependency this useEffect will act as the componentDidMount function
...
return (
...
)
import React, { useEffect } from "react";
function YourComponent() {
useEffect(() => {
retrieveRecipie(e).then((res)=>{
console.log(res);
}
)
}, []);
return (
<div></div>
);
}
export default YourComponent;
让你检索食谱功能
const retrieveRecipie= (yourParams) => {
return fetch(
`URL from where you are fetching data`,
{
method: "GET",
headers: {
Accept: "application/json",
"Content-type": "application/json",
},
body: JSON.stringify(yourParams),
}
)
.then((response) => {
return response.json();
})
.catch((err) => {
console.log(err);
});
};
由于您使用的是 React JS 的 Functional Component,因此您无需手动处理组件生命周期方法。对于功能组件,有 useEffect 钩子来处理组件的生命周期。
import React, { useEffect } from 'react';
export default function GetRecipe(props) {
useEffect(() => {
retrieveRecipe();
},[]);
return <></>;
}
以上代码只会在渲染该组件后调用一次 retrieveRecipe 函数。
我是 React 新手。
我正在尝试 运行 在我的 React 页面加载时进行提取调用以获取一些数据。不过,我不确定我是否正确调用了该事件。
我是这样称呼它的:
export default function GetRecipe(props) {
let { name } = useParams()
const [searchQuery, setSearchQuery] = useState('')
const [recipeName, setRecipeName] = useState('')
const [methodStepsList, setMethodStepsList] = useState([])
const [ingredients, setIngredients] = useState([])
const retrieveRecipe = function (e) {
console.log('getting recipe')
e.preventDefault()
console.log(searchQuery.length)
let queryString
if (searchQuery.length) {
queryString = `http://localhost:3001/getbasicrecipe/?name=${searchQuery}`
} else {
queryString = `http://localhost:3001/getbasicrecipe/?name=${name}`
}
fetch(queryString, {
method: 'GET',
headers: { 'Content-type': 'application/json' },
})
.then((resp) => resp.json())
.then((json) => {
console.log(json)
let result = json
let recipeName = result[0].recipe_name
let recipeMethod = result[0].recipe_method.split(/\r?\n/)
console.log(recipeMethod)
setRecipeName(recipeName)
setMethodStepsList(recipeMethod)
setIngredients(json)
})
}
return (
<div>
<div className="recipe-form-container">
<form className="recipe-form">
[...]
</div>
</form>
</div>
</div>
)
我阅读了有关 componentDidMount()
的内容,但不知道如何将其包含在我的代码中。
谢谢!
如果您使用的是基于 Class 的组件
componentDidMount(){
//Your code here
}
render(){
return ...
}
如果使用函数组件
useEffet(()=>{
//your code here
}, [])
return (...)
这是使用useEffect
hook的经典案例-
与 return 函数使用之前一样 -
useEffect(()=>{ retrieveRecipe(); },[]);
代替componentDidMount
我建议在创建您自己的项目之前玩一下 react.js 教程以掌握它的窍门。
如果您使用的是 class 组件,那么,正如您提到的,您可以像这样使用 componentDidMount() 生命周期方法:
componentDidMount() {
// Runs after the first render() lifecycle
retrieveRecipe();
}
...
render(){
...
}
文档:https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
但是,如果您使用的是功能组件,则应改用 useEffect 钩子,如下所示:
useEffect(() => {
retrieveRecipe();
}, []); // by using an empty array as dependency this useEffect will act as the componentDidMount function
...
return (
...
)
import React, { useEffect } from "react";
function YourComponent() {
useEffect(() => {
retrieveRecipie(e).then((res)=>{
console.log(res);
}
)
}, []);
return (
<div></div>
);
}
export default YourComponent;
让你检索食谱功能
const retrieveRecipie= (yourParams) => {
return fetch(
`URL from where you are fetching data`,
{
method: "GET",
headers: {
Accept: "application/json",
"Content-type": "application/json",
},
body: JSON.stringify(yourParams),
}
)
.then((response) => {
return response.json();
})
.catch((err) => {
console.log(err);
});
};
由于您使用的是 React JS 的 Functional Component,因此您无需手动处理组件生命周期方法。对于功能组件,有 useEffect 钩子来处理组件的生命周期。
import React, { useEffect } from 'react';
export default function GetRecipe(props) {
useEffect(() => {
retrieveRecipe();
},[]);
return <></>;
}
以上代码只会在渲染该组件后调用一次 retrieveRecipe 函数。