zoukankan      html  css  js  c++  java
  • [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>
    );

  • 相关阅读:
    Arrays.fill方法的陷阱
    彻底弄懂最短路径问题
    《c++primer》疑惑记录
    C++ 隐含的this 指针
    c++ 内存分配
    抽象 与 封装 区别
    iconv 文件编码转换
    python中文分词工具——结巴分词
    词形变换和词干提取工具(英文)
    python 绘图工具 matplotlib 入门
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9192475.html
Copyright © 2011-2022 走看看