renmm / blogs

整理自己平时遇到的技术wiki
1 stars 0 forks source link

react-redux的Provider和connect #8

Open renmm opened 5 years ago

renmm commented 5 years ago

connect

当react组件想要使用redux的store里的数据时,使用connect函数。

Provider

最顶层的react组件,提供store数据源,与connect搭配使用。

参考

React 实践心得:react-redux 之 connect 方法详解

renmm commented 5 years ago

redux 基本用法:

import {createStore} from 'redux';

const reducer = (state = {count: 0}, action) => {
  switch (action.type){
    case 'INCREASE': return {count: state.count + 1};
    case 'DECREASE': return {count: state.count - 1};
    default: return state;
  }
}

const actions = {
  increase: () => ({type: 'INCREASE'}),
  decrease: () => ({type: 'DECREASE'})
}

const store = createStore(reducer);

store.subscribe(() =>
  console.log(store.getState())
);

store.dispatch(actions.increase()) // {count: 1}
store.dispatch(actions.increase()) // {count: 2}
store.dispatch(actions.increase()) // {count: 3}