5 Star 3 Fork 1

Gitee 极速下载 / statty

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://github.com/vesparny/statty
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

statty

A tiny and unobtrusive state management library for React and Preact apps

Travis Code Coverage David npm npm JavaScript Style Guide MIT License

The current size of statty/dist/statty.umd.min.js is:

gzip size

The problem

Most of the time, I see colleagues starting React projects setting up Redux + a bunch of middlewares and store enhancers by default, regardless of the project nature.

Despite Redux being awesome, it's not always needed and it may slow down the process of onboarding new developers, especially if they are new to the React ecosystem (I have often seen colleagues being stuck for hours trying to understand what was the proper way to submit a simple form).

React already comes with a built-in state management mechanism, setState(). Local component state is just fine in most of the cases.

In real world apps we often have app state, and sometimes it becomes annoying to pass it down the entire component tree, along with callbacks to update it, via props.

This solution

statty is meant to manage app-wide state and can be thought of as a simplified version of Redux.

It safely leverages context to expose application state to children, along with a function to update it when needed.

The update function acts like Redux dispatch, but instead of an action, it takes an updater function as a parameter that returns the new state.

This way it's easy to write testable updaters and to organize them as you prefer, without having to write boilerplate code.

Table of Contents

Installation

This project uses node and npm. Check them out if you don't have them locally installed.

$ npm i statty

Then with a module bundler like rollup or webpack, use as you would anything else:

// using ES6 modules
import statty from 'statty'

// using CommonJS modules
var statty = require('statty')

The UMD build is also available on unpkg:

<script src="https://unpkg.com/statty/dist/statty.umd.js"></script>

You can find the library on window.statty.

Usage

// https://codesandbox.io/s/rzpxx0w34
import React from 'react'
import { render } from 'react-dom'
import { Provider, State } from 'statty'
import inspect from 'statty/inspect'

// selector is a function that returns a slice of the state
// if not specified it defaults to f => f
const selector = state => ({ count: state.count })

// updaters

// updaters MUST be pure and return a complete new state,
// like Redux reducers
const onDecrement = state => 
  Object.assign({}, state, { count: state.count - 1 })

const onIncrement = state =>
  Object.assign({}, state, { count: state.count + 1 })

// Counter uses a <State> component to access the state
// and the update function used to execute state mutations
const Counter = () => (
  <State
    select={selector}
    render={({ count }, update) => (
      <div>
        <span>Clicked: {count} times </span>
        <button onClick={() => update(onIncrement)}>+</button>{' '}
        <button onClick={() => update(onDecrement)}>-</button>{' '}
      </div>
    )}
  />
)

// initial state
const initialState = {
  count: 0
}

// The <Provider> component is supposed to be placed at the top
// of your application. It accepts the initial state and an inspect function
// useful to log state mutatations during development
// (check your dev tools to see it in action)
const App = () => (
  <Provider state={initialState} inspect={inspect}>
    <Counter />
  </Provider>
)

render(<App />, document.getElementById('root'))

The <Provider> component is used to share the state via context. The <State> component takes 2 props:

  • select is a function that takes the entire state, and returns only the part of it that the children will need
  • render is a render prop that takes the selected state and the update function as parameters, giving the user full control on what to render based on props and state.

State updates happen via special updater functions that take the old state as a parameter and return the new state, triggering a rerender.

An updater function may return the slice of the state that changed or an entire new state. In the first case the new slice will be shallowly merged with old state.

API

<Provider>

Makes state available to children <State>

props

state

object | required

The initial state

inspect

function(oldState: object, newState: object, updaterFn: function)

Use the inspect prop during development to track state changes.

statty comes with a default logger inspired by redux-logger.

<Provider
  state={{count: 0}}
  inspect={require('statty/inspect')}
/>

<State>

Connects children to state changes, and provides them with the update function

props

select

function(state: object) | defaults to s => s | returns object

Selects the slice of the state needed by the children components.

render

function(state: object, update: function) | required

A render prop that takes the state returned by the selector and an update function.

Examples

Examples exist on codesandbox.io:

If you would like to add an example, follow these steps:

  1. Fork this codesandbox
  2. Make sure your version (under dependencies) is the latest available version
  3. Update the title and description
  4. Update the code for your example (add some form of documentation to explain what it is)
  5. Add the tag: statty:example

Inspiration

Tests

$ npm run test

LICENSE

MIT License © Alessandro Arnodo

MIT License Copyright (c) 2017-present Alessandro Arnodo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

statty 是一个小巧而又不引人注目的,用于 React 和 Preact 应用程序的状态管理库 展开 收起
JavaScript
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
JavaScript
1
https://gitee.com/mirrors/statty.git
git@gitee.com:mirrors/statty.git
mirrors
statty
statty
master

搜索帮助