跳转到内容

Lynx

@iostore/lynx 为 ReactLynx 提供与 React 近似的订阅体验,并保持 Lynx 平台语义。

  • Lynx 页面状态订阅与更新。
  • 需要选择器裁剪渲染范围。
  • 需要在移动端高频交互中保持稳定通知节奏。

安装相关依赖(任选一种包管理工具):

Terminal window
npm i @iostore/store @iostore/lynx @lynx-js/react
import { root } from '@lynx-js/react';
import { io } from '@iostore/store';
import { useIO } from '@iostore/lynx';
const count = io(0);
function Counter() {
const value = useIO(count);
return (
<view>
<text>{value}</text>
<view bindtap={() => count.set((v) => v + 1)}>
<text>+1</text>
</view>
</view>
);
}
root.render(<Counter />);
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@lynx-js/react"
}
}
import { useIOSelector } from '@iostore/lynx';
const store = io({ count: 0, other: 0 });
function CountOnly() {
const count = useIOSelector(store, (state) => state.count);
return <text>{count}</text>;
}

如需自定义比较逻辑:

const parity = useIOSelector(store, (state) => ({ p: state.count % 2 }), {
isEqual: (prev, next) => prev.p === next.p,
});
const value = useIO(count, { schedule: 'microtask' });

可选值:sync | microtask | animationFrame

场景API说明
读取 Unit/DeriveduseIO(unitOrDerived, options?)在 ReactLynx 组件中订阅状态。
读取 Scope 片段useIOSelector(scope, selector, options?)精确控制渲染范围。
选择器比较options.isEqual(prev, next)控制对象选择器更新频率。
通知调度options.schedulesync / microtask / animationFrame
写入状态`unit.set(nextupdater)`
// 错误:使用 Web createRoot
// createRoot(document.getElementById('root')!).render(<App />);
// 推荐:使用 Lynx root
root.render(<App />);
// 错误:对象 selector 不加比较函数
const slice = useIOSelector(store, (s) => ({ p: s.count % 2 }));
// 推荐:补 isEqual,减少无效渲染
const slice2 = useIOSelector(store, (s) => ({ p: s.count % 2 }), {
isEqual: (a, b) => a.p === b.p,
});
  • 使用 Lynx 原生标签与事件:view / text / inputbindtap / bindinput
  • 应用入口使用 root.render(...),不要使用 Web 的 createRoot
  • 接入前建议阅读 Lynx 文档总入口:llms.txt