扫码一下
查看教程更方便
recoil 是 react 的状态管理库,因此你需要在 react 工程中安装并使用 recoil。创建 react 项目最为推荐的方式是使用 create react app
:
$ npx create-react-app recoil-study
npx 是 npm 5.2 版本之后支持的 package 运行工具。
这里我们使用 npm
安装 recoil
$ npm install recoil
如需在组件中使用 recoil,则可以将 recoilroot
放置在父组件的某个位置。将它设为根组件为最佳:
import react from 'react';
import {
recoilroot,
atom,
selector,
userecoilstate,
userecoilvalue,
} from 'recoil';
function app() {
return (
);
}
接下来,我们将实现 charactercounter
组件。
一个 atom 代表一个状态。atom 可在任意组件中进行读写。读取 atom 值的组件隐式订阅了该 atom,因此任何 atom 的更新都将致使使用对应 atom 的组件重新渲染:
const textstate = atom({
key: 'textstate', // unique id ()
default: '', // default value (aka initial value)
});
在需要使用的组件中,你应该引入并使用 userecoilstate()
,如下所示:
function charactercounter() {
return (
);
}
function textinput() {
const [text, settext] = userecoilstate(textstate);
const onchange = (event) => {
settext(event.target.value);
};
return (
echo: {text}
);
}
selector 代表一个派生状态,派生状态是状态的转换。你可以将派生状态视为将状态传递给以某种方式修改给定状态的纯函数的输出:
const charcountstate = selector({
key: 'charcountstate', // unique id (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textstate);
return text.length;
},
});
我们可以使用 userecoilvalue()
的 hook,来读取 charcountstate 的值:
function charactercount() {
const count = userecoilvalue(charcountstate);
return <>character count: {count};
}
下面是示例演示结果