Skip to main content

Recoil 快速入门

React 状态管理库。

文章内容: 介绍如何快速的在React项目中使用Recoil

环境准备#

React 环境#

Recoil 是 React 的状态管理库,因此需要准备React项目环境 参考 React 入门快速创建React 项目

Recoil 安装#

npm install recoil或者yarn add recoil或者bower install --save recoil

使用#

使用Recoil实现一个字符串长度统计
hello recoil

创建 CharacterCounter 组件#

src 目录下创建 CharacterCounter.js

import { atom, selector, useRecoilState, useRecoilValue} from 'recoil';
const textState = atom({    key: 'textStateKey', // 唯一ID    default: '', // 默认值});
const charCountState = selector({    key: 'charCountStateKey', // 唯一ID    get: ({get}) => {      const text = get(textState);      return text.length;    },  });
function TextInput() {    const [text, setText] = useRecoilState(textState);      const onChange = (event) => {      setText(event.target.value);    };    return (      <div>        <input type="text" onChange={onChange} />        <br />        Echo: {text}      </div>    );}
export function Counter() {    const count = useRecoilValue(charCountState)    return (      <div>        size: {count}      </div>    );}
export  default TextInput;

index.js中使用#

import { RecoilRoot } from 'recoil';import TextInput, {Counter} from './CharacterCounter';ReactDOM.render(  <React.StrictMode>    <RecoilRoot>      <TextInput/>      <Counter/>    </RecoilRoot>  </React.StrictMode>,  document.getElementById('root'));

说明#

Atom#

一个 atom 代表一个状态。Atom 可在任意组件中进行读写。读取 atom 值的组件隐式订阅了该 atom,因此任何 atom 的更新都将致使使用对应 atom 的组件重新渲染

Selector#

selector 代表一个派生状态,派生状态是状态的转换。你可以将派生状态视为将状态传递给以某种方式修改给定状态的纯函数的输出

useRecoilState#

返回一个数组,第一个元素是 state 的值,第二个元素是一个 setter 函数,调用该函数时会更新为给定 state 的值。

const [text, setText] = useRecoilState(textState);

useRecoilValue#

返回给定 Recoil state 的值

useSetRecoilState#

返回一个 setter 函数,用来更新可写 Recoil state 的值

参考文档#

recoiljs getting-started

useRecoilState

useRecoilValue

useSetRecoilState