如何在react-redux中附加先前状态的更新数据?

时间:2018-04-10 11:41:14

标签: javascript reactjs react-redux

我正在使用react-redux创建一个文件系统应用程序并且是我的新手。 我只想将最新数据附加到以前的数据中。

这是我的代码段

action.js

export function getFolderList(url){
const local_url_LOW = isLocal ? lowJSON : url + '?fileFidelity=LOW';
const  lowRequest = axios.get(local_url_LOW);
return{
    type: GET_FOLDER_LIST,
    payload: lowRequest
};
}

reducer.js

export default function (state = INITIAL_STATE, action) {
switch (action.type) {
    case GET_FOLDER_LIST:
        let data = action.payload.data.Files.File

        folderData = Array.isArray(data) ? data : [data];
        if (folderData.length) {
            for (var i = 0; i < folderData.length; i++) {
                lst.push({
                    id: folderData[i].oid,
                    name: folderData[i].location,
                    type: folderData[i].type,
                    childCount: folderData[i].childCount,
                    createdDate: folderData[i].createdDate,
                    lastModifiedDate: folderData[i].lastModifiedDate,
                    location: folderData[i].location

                });
            }
            return lst;
        }
        break;

}
return state;
}

所以我想返回像... state.chlidFiles:lst这样的数据 所以有人能告诉我锄头这样做。 目前,当我返回的lst数组时,它正在创建具有前一个和第一个arrya的新状态,但我想在以前状态的childFiles中添加这个新的lst数组(或者你可以对一个特定的属性说)

我已经将redux-promise用于承诺。

1 个答案:

答案 0 :(得分:0)

我在这里拍摄一个盲目的建议。我会使用redux-thunk进行异步操作,然后我会发送它并在我的reducer中使用。

<强>动作

const getFolderList = (url) =>
    ( dispatch) => {
        const local_url_LOW = isLocal ? lowJSON : url + '?fileFidelity=LOW';
        const lowRequest = await axios.get(local_url_LOW);
        const data = lowRequest.data.Files.File;
        const folderData = Array.isArray(data) ? data : [data];
        const payload = folderData.map( file => ( {
                id: file.oid,
                name: file.location,
                type: file.type,
                childCount: file.childCount,
                createdDate: file.createdDate,
                lastModifiedDate: file.lastModifiedDate,
                location: file.location,
            } ) );

        dispatch(  {
            type: GET_FOLDER_LIST,
            payload,
        } )
    }

<强>减速器

export default function ( state = INITIAL_STATE, action ) {
    switch ( action.type ) {
    case GET_FOLDER_LIST:
        return { ...state, childFiles: [ ...state.childFiles,  ...action.payload ] };
    default:
        return state;
    }
}