要利用错误驱动的方式进行学习,实际敲代码-->报错-->找问题-->再敲。
首先新建一个Counter组件,设置初始值count = 0,render函数中渲染两个
<button />
和一个<span />
标签。<button/>
的点击事件分别触发计算函数,函数逻辑负责更新this.setState.count<span/>
中渲染this.setState.count数据;
每当state发生变化,React就会重渲染Counter组件和它的子元素。
// Counter.js如下
import React from 'react';
class Counter extends React.Component {
state = { count: 0 }
increment = () => {
this.setState({
count: this.state.count + 1
});
}
decrement = () => {
this.setState({
count: this.state.count - 1
});
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span>{this.state.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
export default Counter;
概念知识:
一、在React中添加Redux
引入两个库:redux和react-redux,每当有人说redux,一准儿就是指这两个库
- redux:是用来管理数据的架构模式,它不关心你用的是什么框架/库,react、vue、甚至jQuery都行;
- react-redux:就是把redux架构和react.js视图层结合起来的库;
- react.js:是将数据渲染成HTML视图的开源js库;
二、Redux的三个核心内容
- Store 就是用来存储应用state tree的一个object对象,state tree包含了应用所有的state。改变 store 内 state 的惟一途径是对它 dispatch 一个 action。
- Action 表示应用中的各类动作或操作,不同的操作会改变应用相应的state状态,说白了就是一个带type属性的对象。
- Reducer 是一个纯函数,包含两个参数,一个state,一个action。两个作用:初始化、计算并返回新的state。
从React重构为Redux的第一步,就是先创建一个store来存储state
// **index.js:**
import { createStore } from 'redux';
const store = createStore();
const App = () => (
<div>
<Counter/>
</div>
);
此时,会报错,因为创建Store需要一个Reducer,所以要写一个Reducer。function reducer(state, action) {
console.log('reducer', state, action);
return state;
}
const store = createStore(reducer);
写完之后再运行,此时我们会看到控制台中出现这样一些数据:
然后我们给state一个初始值,此时控制台输出内容为一个值为0的count对象,和之前的action
const initialState = {
count: 0
};
function reducer(state = initialState, action) {
console.log('reducer', state, action);
return state;
}
此时会看到控制台输出如下结果:
根据文档可知:
Reducer是一个纯函数,包含两个参数,一个state,一个action。
Reducer 不允许有副作用。不能在里面操作 DOM,不能发 Ajax 请求,更不能直接修改 state,它要做的仅仅就是
——负责初始化 state,根据 state 和 action 计算并return新的 state。
然后我们通过dispatch action来改变state
action就是一个带有 type属性为大写字符串 的对象,本身不做任何作用,想让action起作用,就得dispatch它。
dispatch是store的一个内置函数,需要传入一个action,同时它的函数内部会调用我们定义的reducer,并结合当前的state和传入的action,return新的state。
每一次调用 dispatch 最终都会调用 reducer!!!
在index.js中使用dispatch:
const store = createStore(reducer);
store.dispatch({ type: "INCREMENT" });
store.dispatch({ type: "INCREMENT" });
store.dispatch({ type: "DECREMENT" });
store.dispatch({ type: "RESET" });
但此时控制台输出的count:0不变,是因为我们的reducer没有作用于那些actions。所以需要在reducer添加些处理条件。
function reducer(state = initialState, action) {
console.log('reducer:', state, action);
switch(action.type) {
case 'INCREMENT':
return {
count: state.count + 1
};
case 'DECREMENT':
return {
count: state.count - 1
};
case 'RESET':
return {
count: 0
};
default:
return state;
}
}
控制台的count输出产生变化:此时我们已经拥有了一个带 reducer 的 store,并且当接收到 action 时,知道state将如何更新。
接下来我们需要将Redux连接到React!要做到这一点,需要用到react-redux库的两个东西:Provider组件 和 connect函数
Provider组件作为上层组件,将store作为参数注入组件中,store会以props的形式传递给所有子组件。
Provider利用了React Context特性,连接每个组件。
//index.js当前代码
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const initialState = {
count: 0
};
function reducer(state = initialState, action) {
console.log('reducer', state, action);
return state;
}
const store = createStore(reducer);
store.dispatch({ type: "INCREMENT" });
store.dispatch({ type: "INCREMENT" });
store.dispatch({ type: "DECREMENT" });
store.dispatch({ type: "RESET" });
const App = () => (
<Provider store={store}>
<Counter/>
</Provider>
);
但现在Counter组件中还有自己内部的state,想要重构成redux,需要替换成redux里以props方式获取的store数据。
所以移除state初始化,以及increment和decrement内部调用的setState。将refer里的渲染从this.state.count替换成this.props.count。
此时,count并没有渲染,因为目前还没给Count传递count prop,我们需要用到connect函数.
在Count.js组件中引入connect,
并添加映射函数,
然后用connect函数调用,把Count组件包装起来导出。
之前我们只是export了组件本身,现在export的是连接了store的组件
import { connect } from 'react-redux'
//。。。
function mapStateToProps(state) {
return {
count: state.count
};
}
export default connect(mapStateToProps)(Counter);
connect的工作机制
在Redux内部hook,取出整个state,然后把它传入你提供的mapStateToProps函数中。
mapStateToProps的工作机制
在接收到connect传入的整个state后,拿出自己需要的,然后返回对象以props形式传给了你的组件。
——例如上面代码,把state.count的值用count prop传递。实现了从state到props的映射。
connect是一个高阶函数,即当传入参数是函数它时会返回一个函数。如果传入的参数是一个组件,那么返回的就是一个包装过的组件。后者也叫高阶组件。
现在Count组件被connect连接到store上,
我们也获取到了count值,
并且connect还从store传递了dispatch函数。
store的reducer里已经写好了处理条件,所以只需要在Counter组件中调用this.props.dispatch(action)即可。
increment = () => {
this.props.dispatch({type:'INCREMENT'});
};
decrement = () => {
this.props.dispatch({type:'DECREMENT'});
};
至此我们已经完整的走完React重构为Redux的全部过程。