[React] Refactor a connected Redux component to use Unstated

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Refactor a connected Redux component to use Unstated相关的知识,希望对你有一定的参考价值。

In this lesson, I refactor a simple Counter component connected to Redux to use Unstated instead. I explain some of the cognitive overhead of working with Redux and how Unstated can help simplify your application codebase.

Additional Resources https://github.com/jamiebuilds/unstated

 

A basic example for Unstated:

/**
 * Unstated Example
 */
import React from "react";
import ReactDOM from "react-dom";
import Counter from "./components/Counter";
import { Provider, Subscribe, Container } from "unstated";

class CounterContainer extends Container {
  state = {
    count: 0
  };

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  decrement() {
    this.setState({ count: this.state.count - 1 });
  }
}

const ConnectedCounter = () => (
  <Subscribe to={[CounterContainer]}>
    {counter => (
      <Counter
        value={counter.state.count}
        onIncrement={() => counter.increment()}
        onDecrement={() => counter.decrement()}
      />
    )}
  </Subscribe>
);

ReactDOM.render(
  <Provider>
    <ConnectedCounter />
  </Provider>,
  document.getElementById("root")
);

 

We use:

<Subscribe to={[CounterContainer]>

I means we want to keep the state for the component itself.


We can do some interesting things with <Provider> as well like dependency injection:

let counter = new CounterContainer();

render(
  <Provider inject={[counter]}>
    <Counter />
  </Provider>
);

 

 

以上是关于[React] Refactor a connected Redux component to use Unstated的主要内容,如果未能解决你的问题,请参考以下文章

[React] Refactor a connected Redux component to use Unstated

[React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3

[Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose

[Algorithms] Refactor a Linear Search into a Binary Search with JavaScript

[JS Compose] 1. Refactor imperative code to a single composed expression using Box

IDEA快捷键拆解系列(八):Refactor篇