[英]Reuse data with react hooks
我需要用鈎子重用我的應用程序中的數據,所以我創建了一個名為useData
的鈎子
import { useState } from "react";
export default function useData() {
const [message, setMessage] = useState("");
const [type, setType] = useState("error");
return [{ message, type }, { setMessage, setType }];
}
然后我在我的應用程序中使用我的鈎子,如下所示。
function App() {
const [data, action] = useData();
const handleClick = () => {
action.setMessage("Hello message");
action.setType("info");
alert(JSON.stringify(data));
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button className="btn" onClick={handleClick}>
Alert Data
</button>
</div>
);
}
當我第一次單擊按鈕Alert Data
時,它會發出警報
{message: "", type: "error"}
我的期望是
{message: "Hello message", type: "info"}
我在這里做錯了什么? 請讓我知道,有沒有辦法修復此代碼?
這是代碼和框代碼: https ://codesandbox.io/embed/romantic-hugle-zm2e2 ? fontsize =14& hidenavigation =1& theme = dark
感謝您的關注。
您指望在調用onClick
處理程序時立即更新data
,但直到下一次渲染才會如此。 相反,請考慮使用useEffect
鈎子。 在下面的示例中,我還創建了一個有狀態的open
變量來告訴模態何時打開。
function App() {
const [data, action] = useData();
const [open, setOpen] = useState(false);
const handleClick = () => {
action.setMessage("Hello message");
action.setType("info");
setOpen(true);
};
useEffect(() => {
if (open) {
alert(JSON.stringify(data));
setOpen(false);
}
}, [open, data])
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button className="btn" onClick={handleClick}>
Alert Data
</button>
</div>
);
}
在 React.js 中, setState 不是同步函數。 也就是說, setState 不會立即更改狀態。 對於這種情況, setState 有一個帶有完成回調的版本。 您可以使用完成回調定義自定義 Hook。 幸運的是,有一個名為“use-state-with-callback”的 npm 包。
或者您可以編寫如下代碼。
使用Data.js
export default function useData(msg, cb) { const [message, setMessage] = useState(msg); useEffect(() => cb(message), [message]); return [message, setMessage]; }
索引.js
function App() { const callback = (msg) => { alert(JSON.stringify(msg)); } const [message, setMessage] = useData({ content: "", type: "error" }, callback); const handleClick = () => { setMessage({ content: "Hello message", type: "info" }); }; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <button className="btn" onClick={handleClick}> Alert Data </button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
這工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.