纵横研究院React技术专题社区

redux基础

2019-06-04  本文已影响11人  华戈的小书

Redux

1、基本用法:

// reducer
function counter(state = 0, action) {
  switch (action.type) {
    case 'ADD':
      return state + 1;
    case 'SUB':
      return state - 1;
    default:
      return 10;
  }
}

// 创建Store
let store = createStore(counter);
console.log(store.getState()); // 10

// 监听器
function listener() {
  console.log(store.getState()) // 先输出11,在输出10
}

// 订阅事件监听
store.subscribe(listener);

// 分发事件
store.dispatch({ type: 'ADD' });

store.dispatch({ type: 'SUB' });
combineReducers({ reducer1,reducer2 }) //返回合并后的reducer

2、redux的不足:

3、Redux 不只是为 React 而生

react-redux

// 定义Connect,将对应的数据注入
const mapStateToProps = (state) => {
  return { num: state }// 必须返回一个对象
};
const actionCreator = { addAction, subAction, addActionAsync }

App = connect(mapStateToProps, actionCreator)(App)
@connect(
  (state) => ({ num: state.counter }),
  { addAction, subAction, addActionAsync }
)
 npm install --save-dev babel-plugin-transform-decorators-legacy
 "plugins": [
   "transform-decorators-legacy"
]

React-router

npm install --save react-router-dom
<Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path="/" exact component={Dashboard}></Route>
        <Route path="/login" component={Auto}></Route>
        <Route path="/dashboard" component={Dashboard}></Route>
        <!-- <Redirect to="/dashboard"></Redirect>     -->
        <!-- <Link to="/dashboard"></Link> -->
      </Switch>
    </BrowserRouter>
  </Provider>,
上一篇下一篇

猜你喜欢

热点阅读