扫码一下
查看教程更方便
userecoilvalue(state) 返回给定 recoil state 的值。
使用此 hook 会使组件隐式地订阅给定的 state。
function userecoilvalue(state: recoilvalue): t;
当一个组件需要在不写入 state 的情况下读取 state 时,推荐使用该 hook,因为该 hook 可以同时在只读 state 和可写 state 中使用。atom 是可写 state,而 selector 可以是只读,也可以是可写的。更多信息,参考 。
在 react 组件中,使用本 hook 将会订阅该组件,并且在 state 更新时重新渲染该组件。该 hook 在 state 异常或者在异步解析时抛出异常。
import {atom, selector, userecoilvalue} from 'recoil';
const namesstate = atom({
key: 'namesstate',
default: ['', 'ella', 'chris', '', 'paul'],
});
const filterednamesstate = selector({
key: 'filterednamesstate',
get: ({get}) => get(namesstate).filter((str) => str !== ''),
});
function namedisplay() {
const names = userecoilvalue(namesstate);
const filterednames = userecoilvalue(filterednamesstate);
return (
<>
original names: {names.join(',')}
filtered names: {filterednames.join(',')}
);
}