Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A lightweight state container based on Redux

License

NotificationsYou must be signed in to change notification settings

redux-zero/redux-zero

redux zero logo

A lightweight state container based on Redux

Readthe intro blog post


codacybuildnpmdownloadslicensedependencies

Table of Contents

Installation

To install the stable version:

npm i redux-zero

This assumes that you’re usingnpm with a module bundler likewebpack

How

ES2015+:

importcreateStorefrom"redux-zero";import{Provider,connect}from"redux-zero/react";

TypeScript:

import*ascreateStorefrom"redux-zero";import{Provider,connect}from"redux-zero/react";

CommonJS:

constcreateStore=require("redux-zero");const{ Provider, connect}=require("redux-zero/react");

UMD:

<!-- the store --><scriptsrc="https://unpkg.com/redux-zero/dist/redux-zero.min.js"></script><!-- for react --><scriptsrc="https://unpkg.com/redux-zero/react/index.min.js"></script><!-- for preact --><scriptsrc="https://unpkg.com/redux-zero/preact/index.min.js"></script><!-- for vue --><scriptsrc="https://unpkg.com/redux-zero/vue/index.min.js"></script><!-- for svelte --><scriptsrc="https://unpkg.com/redux-zero/svelte/index.min.js"></script>

Example

Let's make an increment/decrement simple application with React:

First, create your store. This is where your application state will live:

/* store.js */importcreateStorefrom"redux-zero";constinitialState={count:1};conststore=createStore(initialState);exportdefaultstore;

Then, create your actions. This is where you change the state from your store:

/* actions.js */constactions=store=>({increment:state=>({count:state.count+1}),decrement:state=>({count:state.count-1})});exportdefaultactions;

By the way, because the actions are bound to the store, they are just pure functions :)

Now create your component. WithRedux Zero your component can focus 100% on the UI and just call the actions that will automatically update the state:

/* Counter.js */importReactfrom"react";import{connect}from"redux-zero/react";importactionsfrom"./actions";constmapToProps=({ count})=>({ count});exportdefaultconnect(mapToProps,actions)(({ count, increment, decrement})=>(<div><h1>{count}</h1><div><buttononClick={decrement}>decrement</button><buttononClick={increment}>increment</button></div></div>));

Last but not least, plug the whole thing in your index file:

/* index.js */importReactfrom"react";import{render}from"react-dom";import{Provider}from"redux-zero/react";importstorefrom"./store";importCounterfrom"./Counter";constApp=()=>(<Providerstore={store}><Counter/></Provider>);render(<App/>,document.getElementById("root"));

Here's the full version:https://codesandbox.io/s/n5orzr5mxj

By the way, you can also reset the state of the store anytime by simply doing this:

importstorefrom"./store";store.reset();

More examples

Actions

There are three gotchas with Redux Zero's actions:

  • Passing arguments
  • Combining actions
  • Binding actions outside your application scope

Passing arguments

Here's how you can pass arguments to actions:

constComponent=({ count, incrementOf})=>(<h1onClick={()=>incrementOf(10)}>{count}</h1>);constmapToProps=({ count})=>({ count});constactions=store=>({incrementOf:(state,value)=>({count:state.count+value})});constConnectedComponent=connect(mapToProps,actions)(Component);constApp=()=>(<Providerstore={store}><ConnectedComponent/></Provider>);

Access props in actions

The initial component props are passed to the actions creator.

constComponent=({ count, increment})=>(<h1onClick={()=>increment()}>{count}</h1>);constmapToProps=({ count})=>({ count});constactions=(store,ownProps)=>({increment:state=>({count:state.count+ownProps.value})});constConnectedComponent=connect(mapToProps,actions)(Component);constApp=()=>(<Providerstore={store}><ConnectedComponentvalue={10}/></Provider>);

Combining actions

There's an utility function to combine actions on Redux Zero:

import{connect}from"redux-zero/react";import{combineActions}from"redux-zero/utils";importComponentfrom"./Component";importfirstActionsfrom"../../actions/firstActions";importsecondActionsfrom"../../actions/secondActions";exportdefaultconnect(({ params, moreParams})=>({ params, moreParams}),combineActions(firstActions,secondActions))(Component);

Binding actions outside your application scope

If you need to bind the actions to an external listener outside the application scope, here's a simple way to do it:

On this example we listen to push notifications that sends data to our React Native app.

importfirebasefrom"react-native-firebase";import{bindActions}from"redux-zero/utils";importstorefrom"../store";importactionsfrom"../actions";constmessaging=firebase.messaging();constboundActions=bindActions(actions,store);messaging.onMessage(payload=>{boundActions.saveMessage(payload);});

Async

Async actions in Redux Zero are almost as simple as sync ones. Here's an example:

constmapActions=({ setState})=>({getTodos(){setState({loading:true});returnclient.get("/todos").then(payload=>({ payload,loading:false})).catch(error=>({ error,loading:false}));}});

They're still pure functions. You'll need to invokesetState if you have a loading status. But at the end, it's the same, just return whatever the updated state that you want.

And here's how easy it is to test this:

describe("todo actions",()=>{letactions,store,listener,unsubscribe;beforeEach(()=>{store=createStore();actions=getActions(store);listener=jest.fn();unsubscribe=store.subscribe(listener);});it("should fetch todos",()=>{nock("http://someapi.com/").get("/todos").reply(200,{id:1,title:"test stuff"});returnactions.getTodos().then(()=>{const[LOADING_STATE,SUCCESS_STATE]=listener.mock.calls.map(([call])=>call);expect(LOADING_STATE.loading).toBe(true);expect(SUCCESS_STATE.payload).toEqual({id:1,title:"test stuff"});expect(SUCCESS_STATE.loading).toBe(false);});});});

Middleware

The method signature for the middleware was inspired by redux. The main difference is that action is just a function:

/* store.js */importcreateStorefrom"redux-zero";import{applyMiddleware}from"redux-zero/middleware";constlogger=store=>(next,args)=>action=>{console.log("current state",store.getState());console.log("action",action.name, ...args);returnnext(action);};constinitialState={count:1};constmiddlewares=applyMiddleware(logger,anotherMiddleware);conststore=createStore(initialState,middlewares);exportdefaultstore;

DevTools

You can setup DevTools middleware in store.js to connect with Redux DevTools and inspect states in the store.

/* store.js */importcreateStorefrom"redux-zero";import{applyMiddleware}from"redux-zero/middleware";import{connect}from"redux-zero/devtools";constinitialState={count:1};constmiddlewares=connect ?applyMiddleware(connect(initialState)) :[];conststore=createStore(initialState,middlewares);exportdefaultstore;

Also, these are unofficial tools, maintained by the community:

TypeScript

You can use theBoundActions type to write your React component props in a typesafe way. Example:

import{BoundActions}from"redux-zero/types/Actions";interfaceState{loading:boolean;}constactions=(store,ownProps)=>({setLoading:(state,loading:boolean)=>({ loading})});interfaceComponentProps{value:string;}interfaceStoreProps{loading:boolean;}typeProps=ComponentProps&StoreProps&BoundActions<State,typeofactions>constComponent=(props:Props)=>(<h1onClick={()=>props.setLoading(!props.loading)}>{props.value}</h1>);constmapToProps=(state:State):StoreProps=>({loading:state.loading});constConnectedComponent=connect<State,ComponentProps>(mapToProps,actions)(Component);constApp=()=>(<Providerstore={store}><ConnectedComponentvalue={10}/></Provider>);

By doing this, TypeScript will know the available actions and their typesavailable on the component's props. For example, you will get a compiler error if youcallprops.setLoding (that action doesn't exist), or if you call itwith incorrect argument types, likeprops.setLoading(123).

Inspiration

Redux Zero was based on thisgist by@developit

Roadmap

  • Make sure all bindings are working for latest versions of React, Vue, Preact and Svelte
  • Add time travel

Help is needed for both of these

Docs

Releases

No releases published

Packages

No packages published

Contributors35


[8]ページ先頭

©2009-2025 Movatter.jp