安装Redux

npm install @reduxjs/toolkit
npm install redux-devtools
npm install react-redux

系统只维护一个state树,一旦state树中的变量发生变化,那么使用过该state变量的组件就会重新渲染,也就是刷新数据。如果程序需要修改state树的值,只能通过触发事件实现,reducers会收到对应的事件,并根据事件中传过来的变量修改state树。每个组件都可注入state树子变量,也都可注入子事件委托,可以在用户点击按钮时触发事件。编程模式为:先定义子变量结构,然后定义该变量的相关事件,事件可以有很多个,每个事件都可以包含一定的用户变量,然后定义子事件处理函数。当变量数据结构和事件处理函数定义好后,就可以把他们注入到组件中了。

The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.

./redux/reducers/index.js

由于使用combineReducers合并reducer,所以store中存储的state变量是一个合成对象,每个reducer以它的名字为键值,以它的值为值存储在store的state中。

export default combineReducers({ logData });

./redux/reducers/logData.js

A reducer's function signature is: (state, action) => newState,该代码主要作用是,当收到一个action事件后,把action事件对应的变量刷新到新的state中,除了action对应的变量被替换为新值后,state变量中其它属性保持不变。运行完该程序后,会得到一个新的state,而不是在原先的state中做部分修改。代码中使用了解构赋值。

  • You can think of a reducer as an event listener which handles events based on the received action (event) type.
  • Redux reducers reduce a set of actions (over time) into a single state.

    const initialState = { messages: [] };

    export default function (state = initialState, action) { switch (action.type) { case LOGDATA: { const { messages } = action.payload; return { …state, messages: messages, }; } default: return state; } }

./redux/actions.js

该代码的作用是动态创建action事件的对象变量,该事件变量会发给reducer生成新的state变量。

export const getLogData = messages => ({
    type: LOGDATA,
    payload: { messages }
});

getLogData的变量可以自定义,只需要在LogFileList.js中调用的时候保持一致就可以了。 export const getLogData = (messages,length) => ({ type: LOGDATA, payload: { messages,length } });

./components/LogFileList.js

该代码的目的是向普通的React组件属性props中注入getLogData函数,getLogData函数在./redux/actions.js中定义,getLogData的作用是把输入的messages变量转换为action事件变量,转化完成后,再把新的事件变量发给./redux/reducers/logData.js处理,整个过程的目的是修改redux的state值。当LogFileList组件需要修改redux的state值时,直接调用函数this.props.getLogData(messages)即可。this.props.getLogData()函数中传入的参数应和./redux/actions.js中定义的变量数量保持一致。

class LogFileList extends React.Component {
...
	this.props.getLogData(messages);
...
}

export default connect(
    null,
    { getLogData }
)(LogFileList);

./components/LogData.js

该代码的目的是向React组件属性props中注入state.logData的变量值,即messages变量。当redux检测到state.logData改变时,会自动刷新属性props的值,并重新渲染组件。

class LogData extends React.Component {
...
	this.props.messages
...
}


const mapStateToProps = state => {
	return state.logData;
};

export default connect(mapStateToProps)(LogData);

./redux/store.js

开启Redux DevTools Extension插件功能,You don’t need to npm install redux-devtools when using the extension (that’s a different lib).

export default createStore(rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());