加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[React] Refactor a connected Redux component to use Unstated

发布时间:2020-12-15 20:28:13 所属栏目:百科 来源:网络整理
导读: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 Resour

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>
);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读