我是新手,現在正在學習制作自定義反應鉤子,我正在嘗試呼叫我在 app.js 檔案中創建的函式,我想在單擊按鈕時使用它。但沒有這樣做。請幫我找出錯誤并理解它。
import React, {
useEffect,
useState
} from "react";
const useRandomJoke = () => {
const [jokes, setJokes] = useState();
useEffect(() => {
const jokeFetch = async() => {
await fetch("https://api.icndb.com/jokes/random")
//we'll run 2 "then"
.then(
// this will give us response and will return inform of res.json
(res) => res.json()
) //.json is a format
.then((data) => {
setJokes(data.value.joke);
}); // now calling data from te returned values in res.json
};
jokeFetch();
}, []);
return jokes;
};
export default useRandomJoke;
//With onClick function
function App() { const [jokes, setJokes] = useState();
return (
<div className="App">
<h1>Random Jokes</h1>
<p>{jokes}</p>
<button onClick={()=>{setJokes(useRandomJoke)}}>
Click for Jokes</button>
</div>
); } export default App;
`
uj5u.com熱心網友回復:
你不能有條件地呼叫 React 鉤子,就像在onClick按鈕的處理程式中一樣,因為這違反了
uj5u.com熱心網友回復:
useRandomJoke是一個自定義鉤子。鉤子應該只在組件的頂層呼叫,因為自定義鉤子已經有joke狀態,你不需要在App組件中額外的狀態。
如果您想在組件渲染后以及每次單擊按鈕時獲得一個新笑話,您可以這樣做:
const useRandomJoke = () => {
const [joke, setJoke] = useState("");
const fetchJoke = useCallback(() => {
fetch("https://api.icndb.com/jokes/random")
.then((res) => res.json())
.then((data) => {
setJoke(data.value.joke);
});
}, []);
return [joke, fetchJoke];
};
export default function App() {
const [joke, fetchJoke] = useRandomJoke();
useEffect(() => {
fetchJoke();
}, [fetchJoke]);
return (
<div className="App">
<h1>Random Jokes</h1>
<p>{joke}</p>
<button onClick={fetchJoke}>Click for a random joke</button>
</div>
);
}
uj5u.com熱心網友回復:
嗯,這里要談的不止一點:
1- 在 React.js 中,您只能在函式主體的頂層呼叫自定義鉤子(反應將任何以關鍵字開頭的函式識別use為鉤子)
function App() {
// top level is here
const randomJokes = useRandomJoke()
const [jokes, setJokes] = useState();
return (
<div className="App">
<h1>Random Jokes</h1>
<p>{jokes}</p>
<button onClick={()=>{setJokes(useRandomJoke)}}>
Click for Jokes
</button>
</div>
); }
export default App;
2-在您的示例中,我知道您希望每次onClick觸發時都有一個新笑話,為此,我認為使用自定義鉤子不是這里的理想解決方案,因為您的自定義鉤子fetchJokes在初始時只運行一次該方法渲染(正如你在你的useEffect鉤子中描述的),我知道很多人提到這useEffect是進行 API 呼叫的地方,但它并不一定適用于所有用例,在你的例子中它很簡單,你沒有useEffect既不使用創建自定義鉤子。
一個可能的簡單解決方案:
function App() {
// we always call hooks at the top level of our function
const [jokes, setJokes] = useState();
const fetchNewJoke = () => {
fetch("https://api.icndb.com/jokes/random")
//we'll run 2 "then"
.then(
// this will give us response and will return inform of
res.json
(res) => res.json()
) //.json is a format
.then((data) => {
setJokes(data.value.joke);
}); // now calling data from te returned values in res.json
};
};
return (
<div className="App">
<h1>Random Jokes</h1>
<p>{jokes}</p>
<button onClick={fetchNewJoke}>Click for Joke</button>
</div>
);
} export default App;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/350035.html
