我还是React-Redux的新手,因此,作为练习,我将重构本教程中发现的React Stopwatch https://medium.com/@peterjd42/building-timers-in-react-stopwatch-and-countdown-bc06486560a2
但这不起作用。
我猜错是在中间件部分。 (我还没有完全理解这个概念。)
const START_TIMER = 'START_TIMER'
const STOP_IT = 'STOP_IT'
const RESUME_IT = 'RESUME_IT'
const startT = () => {
return {
type: START_TIMER
}
}
const stopT = () => {
return {
type: STOP_IT
}
}
const resumeT = () => {
return {
type: RESUME_IT
}
}
const initialState = {
timerOn: false,
timerStart: 0,
timerTime: 0
}
const timerMiddleware = store => next => action => {
if (action.type === 'START_TIMER') {
action.timer =
setInterval(() => store.dispatch({
type: 'START_TIMER',
currentTime: Date.now()
}), 1000)
} else if ( action.type === 'STOP_IT' ) {
clearInterval(action.timer);
}
next(action);
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case START_TIMER:
return {
timerOn: true,
timerTime: state.timerTime,
timerStart: Date.now() - state.timerTime
}
case STOP_IT:
return {
timerOn: false
}
case STOP_IT:
return {
timerStart: 0,
timerTime: 0
}
default: return state;
}
}
const middleware = Redux.applyMiddleware(timerMiddleware)
const store = Redux.createStore(reducer, middleware);
// React:
const Provider = ReactRedux.Provider;
const connect = ReactRedux.connect;
class Presentational extends React.Component {
constructor(props){
super(props);
}
render(){
const { timerTime } = this.props;
let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2)
let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2)
let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2)
let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2)
return(
<div>
{hours} : {minutes} : {seconds} : {centiseconds}<br/>
{this.props.timerOn === false && this.props.timerTime === 0 && (
<button onClick={this.props.startTimer}>Start</button>
)}
{this.props.timerOn === true && (
<button onClick={this.props.stopTimer}>Stop</button>
)}
{this.props.timerOn === false && this.props.timerTime > 0 && (
<button onClick={this.props.startTimer}>Resume</button>
)}
{this.props.timerOn === false && this.props.timerTime > 0 && (
<button onClick={this.props.resetTimer}>Reset</button>
)}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
timerOn: state.timerOn,
timerStart: state.timerStart,
timerTime: state.timerTime
}
}
const mapDispatchToProps = (dispatch) => {
return {
startTimer: () => dispatch({type: START_TIMER }),
stopTimer: () => dispatch({type: STOP_IT }),
resetTimer: () => dispatch({type: RESUME_IT })
};
}
const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);
class AppWrapper extends React.Component {
render() {
return (
<Provider store={store}>
<Container/>
</Provider>
);
}
};
ReactDOM.render(<AppWrapper />, document.getElementById('app'));
我希望秒表开始计数,但是不起作用。 我按下“停止”按钮后,所有数字均为“ aN”。
感谢您的帮助!