import {createEvent, createStore, createEffect, combine, sample} from 'effector'
const nextPost = createEvent()
const getCommentsFx = createEffect(async postId => {
const url = `posts/${postId}/comments`
const base = 'https://jsonplaceholder.typicode.com'
const req = await fetch(`${base}/${url}`)
return req.json()
})
const $postComments = createStore([])
.on(getCommentsFx.doneData, (_, comments) => comments)
const $currentPost = createStore(1)
.on(getCommentsFx.done, (_, {params: postId}) => postId)
const $status = combine(
$currentPost, $postComments, getCommentsFx.pending,
(postId, comments, isLoading) => isLoading
? 'Loading post...'
: `Post ${postId} has ${comments.length} comments`
)
sample({
source: $currentPost,
clock: nextPost,
fn: postId => postId + 1,
target: getCommentsFx,
})
$status.watch(status => {
console.log(status)
})
// => Post 1 has 0 comments
nextPost()
// => Loading post...
// => Post 2 has 5 comments
特征
类型安全
开箱即用的 TypeScript 支持
与框架无关
可以使用任何 UI 或 服务器框架
开发人员友好
简单的API 和 有用的社区
极致的性能
静态初始化可提高运行时的性能
非常小的 bundle size
Effector 提供 small builds 和 支持 tree-shaking
简单、可预测的 JavaScript
没有代理,不需要类。只有您和您的数据