[英]How to use useEffect on button Click?
I've to call useEffect
/ Fetch the data
only when user click on Search Button
otherwise not fetch the data..我必须仅在用户
click on Search Button
时调用useEffect
/ Fetch the data
,否则不会获取数据。
Code:代码:
const App = () => {
const[datas,setDatas] = useState([])
const [space,setSpace] = useState(null)
const [print, setPrint] = useState(false)
function getData(val){
// console.log(val.target.value)
setSpace(val.target.value);
setPrint(false)
}
// console.log(space)
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space
const res = await fetch(url);
const {result} = await res.json();
setDatas(result);
fecthPosts(); //I've to call this fetchPosts() when Btn is CLicked
},[space]);
return(
<div className="App">
{ //Displaying on search
print?
<>
<h2>{space}</h2>
<div>
{datas.map((field) =>
<p>{field.title}</p>
<p>{field.author}</p>
)}
</div>
</>
:null
}
<input type="text" onChange={getData} />
<button onClick={() => { setSpace(true); fetchPosts() }}>search</button>
</div>
)
}
};
export default App;
It's not working Error:它不工作错误:
fetchPosts() is not defined...
I've also tried like this:我也试过这样的:
function trigger(){
useEffect(() => {
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space
const res = await fetch(url);
const {result} = await res.json();
setDatas(result);
fecthPosts(); //I've to call this fetchPosts() when Btn is CLicked
},[space]);
}
<button onClick={() => { setSpace(true); trigger() }}>search</button>
It's not working Error:它不工作错误:
React Hook useEffect has unnecessary dependencies:'space'
/PLZZ help to out... /PLZZ 帮助解决...
为 api 调用创建一个单独的函数,并在您的 UseEffect 函数中调用该函数,然后在按钮单击函数调用 Api 函数并自动获取数据
useCallback is similar to useEffect but is for when a function needs a callback, like what you're doing here onClick. useCallback 与 useEffect 类似,但适用于函数需要回调的情况,例如您在 onClick 中所做的。 useEffect is used in response to some prop changing not an action taken by a user.
useEffect 用于响应某些道具更改而不是用户采取的操作。
I initialized shouldFetchData = false
.我初始化
shouldFetchData = false
。 Once the button is clicked, I changed it's value;单击按钮后,我更改了它的值;
shouldFetchData = true
. shouldFetchData = true
。 Inside useEffect I called fetchPosts()
only when shouldFetchData
is true
.在 useEffect 内部,我仅在
shouldFetchData
为true
时才调用fetchPosts()
。
import React, { useState } from "react";
const App = () => {
const [datas, setDatas] = useState([])
const [shouldFetchData, setShouldFetchData] = useState(false);
const [space, setSpace] = useState(null)
const [print, setPrint] = useState(false)
function getData(val) {
// console.log(val.target.value)
setSpace(val.target.value);
setPrint(false)
}
// console.log(space)
const fecthPosts = async () => {
let initial_url = `http://localhost:4000/search`
let url = initial_url + "?text=" + space
const res = await fetch(url);
const { result } = await res.json();
setDatas(result);
fecthPosts(); //I've to call this fetchPosts() when Btn is CLicked
}
useEffect(() => {
if(shouldFetchData) {
fecthPosts();
}
}, [space]);
return (
<div className="App">
{
print ?
<>
<h2>{space}</h2>
<div>
{datas.map((field) =>
<>
<p>{field.title}</p>
<p>{field.author}</p>
</>
)}
</div>
</>
: null
}
<input type="text" onChange={getData} />
<button onClick={() => {
setSpace(true);
setShouldFetchData(true);
}}>search</button>
</div>
)
};
export default App;
I found a few syntax errors in your code, so I hope I did what you intended.我在你的代码中发现了一些语法错误,所以我希望我做了你想要的。 If This is not the proper way to do this or if there exists a better way, please let me know.
如果这不是执行此操作的正确方法或存在更好的方法,请告诉我。 I'd be happy to learn.
我会很乐意学习。
You have to set your fetchPosts outside of the useEffect
.您必须在 useEffect 之外设置
useEffect
。 Then, you can use a new state search
to track any click on the button.然后,您可以使用新的状态
search
来跟踪按钮上的任何点击。
const App = () => {
const [datas, setDatas] = useState([]);
const [space, setSpace] = useState(null);
const [print, setPrint] = useState(false);
const [search, setSearch] = useState(false);
const fetchPosts = async () => {
let initial_url = `http://localhost:4000/search`;
let url = initial_url + "?text=" + space;
const res = await fetch(url);
const { result } = await res.json();
setDatas(result);
};
function getData(val) {
setSpace(val.target.value);
setPrint(false);
}
useEffect(() => {
fetchPosts(); // fecthPosts is called each time space changed
}, [search]);
return (
<div className="App">
{
//Displaying on search
print ? (
<>
<h2>{space}</h2>
<div>
{datas.map((field) => (
<>
<p>{field.title}</p>
<p>{field.author}</p>
</>
))}
</div>
</>
) : null
}
<input type="text" onChange={getData} />
<button onClick={() => setSearch(!search)}>search</button>
</div>
);
};
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.