如何在加载组件时停止检索数据



我只希望在单击生成笑话(单击此处获取笑话(按钮后显示数据,但是一旦页面加载就会检索到数据。我该如何阻止这种情况?

`import React, { useState, useEffect } from "react";
function App() {
const [joke, getJoke] = useState(" ")
const newJoke = () => {
fetch("http://api.icndb.com/jokes/random")
.then(result => result.json())
.then(result2 => {
console.log(result2)
getJoke(result2.value.joke)
})
}
useEffect(() => {
newJoke()
}, [])
return (
<div className="jokeSection">
<h1>Chuck norris jokes</h1>
<h3>{joke}</h3>
<button onClick={() => newJoke()}>Click here for a chuckle</button>
</div>
)
}
export default App;`

这是一种好的编码方式吗?我应该使用不同的函数,如componentDidMount吗?

`import React, { useState, useEffect } from "react";
function App() {
const [joke, getJoke] = useState(" ")
const newJoke = () => {
fetch("http://api.icndb.com/jokes/random")
.then(result => result.json())
.then(result2 => {
console.log(result2)
getJoke(result2.value.joke)
})
}
useEffect(() => {
}, [])
return (
<div className="jokeSection">
<h1>Chuck norris jokes</h1>
<h3>{joke}</h3>
<button onClick={() => newJoke()}>Click here for a chuckle</button>
</div>
)
}
export default App;`

将其从useEffect中删除并保留在单击上,这应该可以做到。如注释中所述,useEffect将在每次页面加载时运行。

我宁愿为笑话切换和笑话数据维护 2 个状态,如下所示。

名为 useEffect 的效果钩子用于使用 axios 从 API 获取数据,并使用状态钩子的更新函数将数据设置在组件的本地状态。承诺解析发生在异步/等待中。

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
function App() {
const [joke, setJoke] = useState(0);
const [jokeData, setJokeData] = useState("");
function newJoke(){
setJoke(joke=>joke+1);
}
useEffect( () => {
(async function loadJoke() {
if(joke>0){ 
const response=await axios.get('https://api.icndb.com/jokes/random');
setJokeData(response.data.value.joke);
}
})();
}, [joke]);
return (
<div className="jokeSection">
<h1>Chuck norris jokes</h1>
<h3>{jokeData}</h3>
<button onClick={() => newJoke()}>Click here for a chuckle</button>
</div>
);
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

相关内容

  • 没有找到相关文章

最新更新