我正在尝试在Redux状态下覆盖一个数组的特定值。我已经获得了索引以及新文本的值(value)。我只是不确定覆盖先前文本的最佳方法。到目前为止,这是我的 reducer 。 UPDATE_LINK是我遇到的问题。

export function linkList(state = [], action) {
    switch(action.type) {
        case 'ADD_LINK':
            var text = action.text;
            console.log('Adding link');
            console.log(text);
            return {
                ...state,
                links: [text, ...state.links]
            };
        case 'DELETE_LINK':
            var index = action.index;
            console.log('Deleting link');
            return {
                ...state,
                links: [
                    ...state.links.slice(0, index),
                    ...state.links.slice(index + 1)
                ],
            };
        case 'UPDATE_LINK':
            var index = action.index;
            var newText = action.newText;
            console.log(action.newText);
            console.log(action.index);
            return {
                ...state,
                // How do I update text?
            }
        default:
            return state;
    }
};

export default linkList;

最佳答案

您可以使用Array.protoype.map返回现有条目(如果可用)和新条目(索引匹配):

var index = action.index;
var newText = action.newText;
return {
    ...state,
    links: state.links.map((existingLink, currentIndex) => index === currentIndex ? newText : existingLink)
}

或者,按照您现有的DELETE_LINK逻辑:
return {
    ...state,
    links: [
        ...state.links.slice(0, index),
        newText,
        ...state.links.slice(index + 1)
    ],
};

关于javascript - 如何使用redux替换数组中的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40866715/

10-08 22:14
查看更多