返回

从零开始手写React/React-Redux核心API

前端

Redux是一种状态管理框架,它可以帮助开发者管理应用的状态,Redux的API很小,我们尝试手写React/Redux/React-Redux的核心API,通过手写Redux/React-Redux核心API,我们能更好地理解Redux的原理,加深对Redux的认识,从而更好地使用Redux来构建应用程序。

首先,我们来看一下Redux的核心API。Redux的核心API包括createStore、getState、dispatch、subscribe。

createStore是用来创建Redux store的,getState是用来获取Redux store中状态的,dispatch是用来派发action的,subscribe是用来监听Redux store中状态变化的。

function createStore(reducer) {
  let state = null;
  const listeners = [];

  const getState = () => state;

  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach((listener) => listener());
  };

  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners.filter((l) => l !== listener);
    };
  };

  dispatch({});

  return { getState, dispatch, subscribe };
}

接下来,我们来看一下React-Redux的核心API。React-Redux的核心API包括Provider、connect。

Provider是用来把Redux store提供给React组件的,connect是用来把Redux store中的状态映射到React组件的props的。

class Provider extends React.Component {
  render() {
    return React.createElement(
      React.Context.Provider,
      { value: this.props.store },
      this.props.children
    );
  }
}

const connect = (mapStateToProps, mapDispatchToProps) => (WrappedComponent) => {
  return class ConnectComponent extends React.Component {
    constructor(props, context) {
      super(props, context);
      this.state = mapStateToProps(context.store.getState());
    }

    componentDidMount() {
      this.unsubscribe = context.store.subscribe(() => {
        this.setState(mapStateToProps(context.store.getState()));
      });
    }

    componentWillUnmount() {
      this.unsubscribe();
    }

    render() {
      return React.createElement(
        WrappedComponent,
        { ...this.props, ...this.state }
      );
    }
  };
};

通过以上API我们就可以构建一个Redux应用了。

以下是使用Redux和React-Redux构建的一个简单的计数器应用:

// reducer.js
const reducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

// store.js
const store = createStore(reducer);

// App.js
class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Count: {this.props.count}</h1>
        <button onClick={() => store.dispatch({ type: 'INCREMENT' })}>+</button>
        <button onClick={() => store.dispatch({ type: 'DECREMENT' })}>-</button>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    count: state,
  };
};

export default connect(mapStateToProps)(App);

通过这个简单的计数器应用,我们可以看到Redux和React-Redux是如何工作的。Redux是一个状态管理框架,它可以帮助开发者管理应用的状态,React-Redux是Redux的React版本,它可以把Redux store中的状态映射到React组件的props中。