如何在 redux 中获取之前的状态

How to get previous state in redux

我想将状态设置为他以前的值 单击按钮......将 redux-state 更改为以前的 redux-state

减速器文件

export var key = (state = 0, action) => {
    if (action.type === 'changeKey') {
        return action.playload
    }
    else {
        return state
    }
}

动作文件

export var keyAction = (name) => {
    return {
        type: 'changeKey',
        playload: name,
    }
}

3 个文件

<Text onPress={()=>{
//what i need to write here ???
}}> Set redux-state to previous value of redux-state</Text>

你应该发送你的 redux 动作

import { useDispatch } from 'react-redux'


const FC = () => {
    const dispatch = useDispatch()

    return (
        <Text onPress={() => dispatch(keyAction("Whosebug"))}>
            Set redux-state to previous value of redux-state
        </Text>
    )
}

您还写了 playload 而不是 payload

您可以在 Dispatch action 类型之前获取之前的状态

export const keyAction = (name) => (dispatch, getState) => {
    const previousValue = getState().REDUCER_NAME

    console.log(previousValue);

    return dispatch({
        type: 'changeKey',
        playload: name
    })
}

您可以使用 redux-undo (https://github.com/omnidan/redux-undo) or implement your own custom logic following this documentation https://redux.js.org/usage/implementing-undo-history

我制作了数组列表——每次我添加键时它都会将值添加到前一个数组中

当我想将 redux-state 设置为之前的状态时,我只需删除数组的最后一项,并将 redux-state 设置为该数组的最后一项

var list = [0]

export var keyAction = (name) => {
    list = [...list, name]
    return {
        type: 'changeKey',
        playload: name,
    }
}
export var keyBackAction = () => {
    list.splice(-1)
    return {
        type: 'getBack',
        playload: list[list.length - 1],
    }
}