使用React Easy状态重新创建挂钩

分享于 

3分钟阅读

Node.js

  繁體

钩子& React Easy状态的基本示例

看看如何使用钩子和React Easy状态设置文档标题。

钩子版本


import React, { useState, useCallback, useEffect } from "react";

export default () => {
 const [title, setTitle] = useState("App title");
 const onChange = useCallback(ev => setTitle(ev.target.value), [setTitle]);

 useEffect(() => {
 document.title = title;
 }, [title]);

 return <input value={title} onChange={onChange} />;
};


codeSandBox Demo

React Easy State版本


import React from "react";
import { view, store, autoEffect } from "@risingstack/react-easy-state";

export default view(() => {
 const title = store({
 value: "App title",
 onChange: ev => (title.value = ev.target.value)
 });

 autoEffect(() => (document.title = title.value));

 return <input value={title.value} onChange={title.onChange} />;
});


codeSandBox Demo

autoEffect替换了useEffect hook,而store则替换了,

可重用性

幸运的是,Hooks旨在捕获可重用的逻辑。

钩子版本

useTitle.js:


import { useState, useCallback, useEffect } from "react";

export default function useTitle(initalTitle) {
 const [title, setTitle] = useState(initalTitle);
 const onChange = useCallback(ev => setTitle(ev.target.value), [setTitle]);

 useEffect(() => {
 document.title = title;
 }, [title]);

 return [title, onChange];
}


App.js:


import React from "react";
import useTitle from "./useTitle";

export default () => {
 const [title, onChange] = useTitle();
 return <input value={title} onChange={onChange} />;
};


codeSandBox Demo

React简单状态版本

titleStore.js:


import { store, autoEffect } from "@risingstack/react-easy-state";

export default function titleStore(initalTitle) {
 const title = store({
 value: initalTitle,
 onChange: ev => (title.value = ev.target.value)
 });

 autoEffect(() => (document.title = title.value));

 return title;
}


App.js:


import React from "react";
import { view } from "@risingstack/react-easy-state";
import titleStore from "./titleStore";

export default view(() => {
 const title = titleStore("App title");
 return <input value={title.value} onChange={title.onChange} />;
});


codeSandBox Demo


STA  react  STAT  State  钩子  hooks  
相关文章