繁体   English   中英

Redux Toolkit 中的条件调度操作

[英]Conditionally dispatching actions in Redux Toolkit

我正在使用 Redux Toolkit 开发我的番茄钟。

我应该有三个输入,我可以自定义番茄时间 (1)、长 (2) 和短时间 (3) 的分钟数。

因此,我创建了<Input/>组件并在弹出窗口中渲染了 3 次。

//NumberInput.js

import React from 'react';
import styled from "./NumberInput.module.css";

const NumberInput = ({label}) => {
    return (
        <div className={styled.inputContainer}>
            <label htmlFor="">{label}</label>
            <input className={styled.input} type="number" min={0}/>
            <button className={styled.inputBtn} type="button">
                <svg width="14" height="7" viewBox="0 0 14 7" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1 6L7 2L13 6" stroke="#1E213F" strokeOpacity="0.25" strokeWidth="2"/>
                </svg>
            </button>
            <button className={styled.inputBtn} type="button">
                <svg width="14" height="7" viewBox="0 0 14 7" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1 1L7 5L13 1" stroke="#1E213F" strokeOpacity="0.25" strokeWidth="2"/>
                </svg>
            </button>
        </div>
    );
};

export default NumberInput;

而且我有 timerSlice.js 我保存我的时间数据:

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    pomodoroMinutes: 25,
    shortBreakMinutes: 5,
    longBreakMinutes: 15,
}

const timerSlice = createSlice({
    name: 'timer',
    initialState,
    reducers: {}
})

export default timerSlice.reducer;

问题是我无法猜测如何根据用户交互的输入来调度不同的操作。 例如,如果我尝试增加/减少长休息时间,我需要调度一个操作来更改切片中的longBreakMinutes字段; shortBreakMinutes的情况下另一个动作。

您可以创建一个数组来区分输入和调度操作,方法是按值标识输入以保存这些更改。

const ParentComponent = () => {
const minuteType = ['long', 'short']; 

minuteType.map((type, idx) =>  {
    return <NumberInput type={type} key={idx}/>
})
}

const NumberInput = ({label, type}) => {
const [inputVal, setInputVal] = useState('');
const dispatch = useDispatch(); 

const saveChanges = () => {
    if (type === 'long') {
        dispatch(saveLongMinutes(inputVal))
    }
    if (type === 'short') { 
        dispatch(saveShortMinutes(inputVal))
    }
}

return (
 
    {/* Other Content */}
        <input className={styled.input} type="number" min={0} onChange={(event) => setInputVal(event.target.value)}/>
        <button type="button" onclick={saveChanges}>
        Save
    </button>
);

};

Redux 商店

const timerSlice = createSlice({
name: 'timer',
initialState,
reducers: {
    saveLongMinutes(state, action) {
        state.longBreakMinutes = action.payload
    }, 
    saveShortMinutes(state, action) {
        state.shortBreakMinutes = action.payload
    }  
}
})
export const { saveLongMinutes, saveShortMinutes } = timerSlice.actions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM