返回
用React, Redux, Redux-Thunk从头到尾打造一个计算器
前端
2023-09-12 13:23:37
前言
Redux是目前最流行的前端状态管理库之一,它提供了一种集中管理应用程序状态的方式,使应用程序更容易维护和调试。Redux-Thunk是一个Redux的中间件,它允许您在Redux中执行异步操作。
创建React项目
首先,我们需要创建一个React项目。您可以使用create-react-app工具来创建一个新的React项目:
npx create-react-app redux-calculator
添加Redux和Redux-Thunk
接下来,我们需要在项目中添加Redux和Redux-Thunk。您可以使用以下命令来安装它们:
npm install redux react-redux redux-thunk
创建Redux Store
在项目中,我们需要创建一个Redux Store来管理应用程序的状态。Store是一个对象,它包含了应用程序的所有状态数据。
// src/store.js
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import thunk from 'redux-thunk';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
export default store;
创建Redux Reducers
Reducers是Redux用来处理动作并更新状态的函数。
// src/reducers/index.js
import { combineReducers } from 'redux';
import calculatorReducer from './calculatorReducer';
const rootReducer = combineReducers({
calculator: calculatorReducer
});
export default rootReducer;
// src/reducers/calculatorReducer.js
const initialState = {
result: 0,
operand1: 0,
operand2: 0,
operator: '+'
};
const calculatorReducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD':
return { ...state, result: state.operand1 + state.operand2 };
case 'SUBTRACT':
return { ...state, result: state.operand1 - state.operand2 };
case 'MULTIPLY':
return { ...state, result: state.operand1 * state.operand2 };
case 'DIVIDE':
return { ...state, result: state.operand1 / state.operand2 };
case 'SET_OPERAND1':
return { ...state, operand1: action.payload };
case 'SET_OPERAND2':
return { ...state, operand2: action.payload };
case 'SET_OPERATOR':
return { ...state, operator: action.payload };
default:
return state;
}
};
export default calculatorReducer;
创建Redux Actions
Actions是Redux用来触发状态更新的函数。
// src/actions/calculatorActions.js
export const add = () => ({ type: 'ADD' });
export const subtract = () => ({ type: 'SUBTRACT' });
export const multiply = () => ({ type: 'MULTIPLY' });
export const divide = () => ({ type: 'DIVIDE' });
export const setOperand1 = (operand1) => ({ type: 'SET_OPERAND1', payload: operand1 });
export const setOperand2 = (operand2) => ({ type: 'SET_OPERAND2', payload: operand2 });
export const setOperator = (operator) => ({ type: 'SET_OPERATOR', payload: operator });
使用Redux和Redux-Thunk
现在,我们需要在组件中使用Redux和Redux-Thunk。
// src/App.js
import React, { useState } from 'react';
import { connect } from 'react-redux';
import { add, subtract, multiply, divide, setOperand1, setOperand2, setOperator } from './actions/calculatorActions';
const App = ({ result, operand1, operand2, operator, setOperand1, setOperand2, setOperator, add, subtract, multiply, divide }) => {
const [input, setInput] = useState('');
const handleOperand1Change = (e) => {
setOperand1(e.target.value);
};
const handleOperand2Change = (e) => {
setOperand2(e.target.value);
};
const handleOperatorChange = (e) => {
setOperator(e.target.value);
};
const handleCalculate = () => {
switch (operator) {
case '+':
add();
break;
case '-':
subtract();
break;
case '*':
multiply();
break;
case '/':
divide();
break;
default:
break;
}
};
return (
<div className="App">
<input type="number" value={operand1} onChange={handleOperand1Change} />
<select value={operator} onChange={handleOperatorChange}>
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" value={operand2} onChange={handleOperand2Change} />
<button onClick={handleCalculate}>Calculate</button>
<div>Result: {result}</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
result: state.calculator.result,
operand1: state.calculator.operand1,
operand2: state.calculator.operand2,
operator: state.calculator.operator
};
};
const mapDispatchToProps = (dispatch) => {
return {
add: () => dispatch(add()),
subtract: () => dispatch(subtract()),
multiply: () => dispatch(multiply()),
divide: () => dispatch(divide()),
setOperand1: (operand1) => dispatch(setOperand1(operand1)),
setOperand2: (operand2) => dispatch(setOperand2(operand2)),
setOperator: (operator) => dispatch(setOperator(operator))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
运行应用程序
现在,我们可以运行应用程序了:
npm start
总结
本文带领您一步步地构建了一个使用React, Redux, Redux-Thunk构建的计算器应用程序。通过本教程,您应该对Redux, Redux-Thunk和React在构建复杂前端应用程序方面的应用有了一个深入的理解。