代码: https://github.com/JanYLee/recruit-app/tree/demo/use-redux-in-react
在没有使用连接库比如react-redux, 手动连接时, 步骤应该是这样:
- store.dispatch 方法传递给组件, 在组件内部派发事件
- subscribe订阅render方法, 监听每次重新渲染
- redux内相关内容移动到单独文件管理, 如index.redux.js
创建xxx.redux.js状态文件
把之前和操作状态有关的函数和变量放于一个文件index.redux.js
const ADD_COUNTER = 'add';const DELETE_COUNTER = 'delete';// 新建store// 通过reducer生成// 根据老的state和action 生成新的stateexport function counter(state = 0, action) {switch (action.type) {case ADD_COUNTER:return state + 1;case DELETE_COUNTER:return state - 1;default:return 10;}}// actionCreaterexport function addCounter() {return { type: ADD_COUNTER };}export function deleteCounter() {return { type: DELETE_COUNTER };}
上面这个文件里包含了reducer, 就是那个counter函数, 以及action, 然后把reducer和action导出
创建store以及订阅方法
- 在index.js中, 从redux.js文件中得到reducer, 用于创建store, 并传入App这个组件
- 从redux.js得到action(addCounter和deleteCounter), 也传入App这个组件
- 然后需要在store中订阅方法subscribe, 每次store内容改变就重新render ```javascript import React from ‘react’; import ReactDOM from ‘react-dom’; import { createStore } from ‘redux’;
import { counter, addCounter, deleteCounter } from ‘./index.redux’;
import App from ‘./App.jsx’;
// 新建store const store = createStore(counter);
function render() {
ReactDOM.render(
// 监听每次修改store store.subscribe(render);
<a name="NdkB4"></a>## 创建组件并在内部派发方法- 创建App.jsx文件, 并导出- 从props中获取store和action- 从store中获取需要的state, 从组件中派发(store.dispatch) action```javascriptimport React, { Component } from 'react';export default class App extends Component {render() {const { store, addCounter, deleteCounter } = this.props;const num = store.getState();return(<div><h1>Counter</h1><p>现在的计数器: {num}</p><button onClick={() => store.dispatch(addCounter())}>新增计数</button><button onClick={() => store.dispatch(deleteCounter())}>减少计数</button></div>)}}
完成连接
这样就手动的完成了在react内部使用redux;当然自己写起来比较痛苦
效果: 
