引言
这是一个基础的教程. 希望可以通过这个教程, 让很多初学 Redux 这个工具的小伙伴可以很轻松的上手.
在自己研究的这一过程中, 主要参考了下列文章, 请大家耐心的去读一读, 有助于更系统清晰的理解 Redux:
阮一峰老师的文章: Redux 入门教程 (一): 基本用法 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
redux 官方网站: github/examples/counter 简单例子 https://github.com/reduxjs/redux/tree/master/examples
理解的心酸历程
store
说到 store , 由于之前对 vue 比较熟悉, 我就类比去想象 vuex 中的 store . 回到正题, 在 Redux 中仅存一个 store , 用于跟组件中绑定.
- import { Provider } from 'react-redux'
- import { createStore } from 'redux'
- import { composeWithDevTools } from 'redux-devtools-extension'; // 这是 Chrome 调试工具, 推荐安装
- const store = createStore(
- rootReducer,
- composeWithDevTools()
- )
- ReactDOM.render(
- <Provider store={store}>
- <App />
- </Provider>,
- document.getElementById('root')
- );
复制代码
action
定义 action, 说白了是一个方法的集合. 这些集合的方法描述了用户的操作动作. 由于 用户 在界面上操作 DOM, 实际上是在 view 层中不断的做操作. js 通过调用这些方法来完成 action 操作.
- export const addTodo = (time) => {
- return {
- type: "ADD_TODO",
- time
- }
- }
- export const addTodoUp = (time) => {
- return {
- type: "ADD_TODO_LIST",
- time
- }
- }
复制代码
reducers
这里的 reducers , 我认为相当于大脑. 就好像 action 肢体上的操作, 通过神经传递给了大脑, 那么大脑就应该对这些 action 进行操作.下面的 combineReducers 实际上起到了整合的作用, 将一下细碎的 reducers 整合在一起.
- import { combineReducers } from 'redux';
- import user from './user.js';
- import list from './list.js';
- export default combineReducers({
- user,
- list
- })
复制代码
回到组件内部
截止到现在, 人已经做了动作 action, 大脑也反应了 reducers, 更改了大脑中的记忆 store, 那么返回给肢体上的怎么去实施呢? 操作如下:
- import React, { Component } from 'react';
- import './App.CSS';
- import { connect } from 'react-redux'
- import { addTodo, addTodoUp } from './actions/index.js'
- class App extends Component {
- _init = () => {
- let { dispatch } = this.props;
- dispatch(addTodo(3))
- }
- _init2 = () => {
- let { dispatch } = this.props;
- dispatch(addTodoUp(3))
- }
- componentDidMount () {
- }
- render() {
- let { time } = this.props;
- return (
- <div className="App">
- <p>{ time }</p>
- <button onClick={ this._init }> 点击增加 </button>
- <button onClick={ this._init2 }> 点击增加 111111</button>
- </div>
- );
- }
- }
- function mapStateToProps(state) {
- return { time: state.user + state.list }
- }
- export default connect(mapStateToProps)(App);
复制代码
首先需要从 actions 中去调用动作的方法, 这一点毋庸置疑. 由于我们的 store 存放在跟组件中, 所以我们可以通过 this.props 获取值. 不仅仅如此, 在 this.props 中, 我们还能获取到触发 action 的关键字 dispatch. 这里面有几个关键字需要注意下:
mapStateToProps
mapStateToProps 是一个函数, 用于建立组件跟 store 的 state 的映射关系 作为一个函数, 它可以传入两个参数, 结果一定要返回一个 object .
connect
上面定义的关联 state 和 action 的方法需要绑定到当前组件上面.
最后我想说:
不求认同, 但求指正, 指导. 大家也可以来我的博客站发表对文章中理解有歧义的地方提出自己的看法.
来源: https://juejin.im/post/5b471060e51d45190d551f97