如何使用redux替换数组中的值?

max*_*ver 2 javascript redux

我正在尝试覆盖我的Redux状态中的一个特定值,这是一个数组.我已经获得了索引以及新文本的值.我只是不确定覆盖以前文本的最佳方法.到目前为止,这是我的减速机.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;
Run Code Online (Sandbox Code Playgroud)

Cod*_*gue 6

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

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

或者,遵循现有DELETE_LINK逻辑:

return {
    ...state,
    links: [
        ...state.links.slice(0, index),
        newText,
        ...state.links.slice(index + 1)
    ],
};
Run Code Online (Sandbox Code Playgroud)

  • 您可能还想查看Redux文档的["Structuring Reducers"](http://redux.js.org/docs/recipes/StructuringReducers.html)部分中的一些信息.特别是,请参阅[ "不可变更新模式"](http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html)页面. (2认同)