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

  • 相关阅读:
    java控制台输入
    冒泡排序
    选择排序
    Json数组去重
    HTTP状态码详解
    根据json对象的值替换json数组里的值
    用户中心页面
    正则表达式
    vue-router如何根据不同的用户给不同的权限
    vue2.0+element+node+webpack搭建的一个简单的后台管理界面
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9192475.html
Copyright © 2020-2023  润新知