之前说React Hooks可以没有class直接work。这是useState
的写法和对应的class写法:
再看一眼 useState Hook
· One min read
之前说React Hooks可以没有class直接work。这是useState
的写法和对应的class写法:
在React(typescript)中渲染需即时加载的元素。主要思路是使用useEffect Hook加载内容,而后使用useState Hook在加载完成时重新渲染界面。简短的代码描述如下:
interface AsyncCompomentProps {
func: () => Promise<JSX.Element>;
default?: JSX.Element;
}
function AsyncComponent(props: AsyncCompomentProps) {
const [loaded, setLoaded] = useState<JSX.Element>(null);
useEffect(() => {
props.func().then((result) => {
setLoaded(result);
});
}, []);
return loaded ? loaded : props.default ?? <div>Loading...</div>;
}
<AsyncComponent
func={async () => {
await new Promise((r) => setTimeout(r, 3000));
return <div>hi</div>;
}}
default={<div>I'm loading...</div>}
/>;
Hooks are a new addition in React 16.8. They let you "hook into" React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. In older React, it's hard to reuse stateful logic between components. The older React doesn't offer a way to "attach" reusable behavior to a component. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.
There are nine of them:
Hook | Motivation |
---|---|
useState |