代码之家  ›  专栏  ›  技术社区  ›  Boris K

基于后端返回的Redux更新数组中的一个元素

  •  0
  • Boris K  · 技术社区  · 8 年前

    我有一个React Redux应用程序,正在构建更新功能。我有一个状态图列表,并更新其中一个。成功的更新API调用将更新的绘图作为响应获取。如何用状态更新的绘图替换旧绘图?

    现在,这是我的减速机。我看到更新的绘图被记录下来,但除非我重新加载,否则它不会在状态中被替换。成功后,我始终可以从后端重新加载整个绘图列表,但希望避免不必要的调用。

    case UPDATED_PLOT:
                action.payload.id = action.payload._id;
                console.log('updated plot received by reducer: ', action.payload);
                return {
                    ...state,
                    filteredPlots: state.filteredPlots.map(
                        plot => (plot.id == action.payload.id ? action.payload : plot)
                    )
                };
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   hedgepigdaniel    8 年前

    我觉得你的减速机代码很好。您是如何得出redux状态更新的结论的?您是否尝试过安装 redux-dev-tools 确保状态未更新?

    如果确定状态已更新,则可能需要检查组件是否已重新渲染。您可以在特定组件中插入componentWillUpdate()。此外,值得检查文档 react-redux ,尤其是“纯”选项。

        2
  •  0
  •   Nidhi Agarwal    8 年前

    尝试以下操作:

    case UPDATED_PLOT:
        action.payload.id = action.payload._id;
        const new_filtered_plots = state.filteredPlots.map(plot => {
           return plot.id == action.payload.id ? action.payload : plot
        });
        return Object.assign({}, state, {filteredPlots: new_filtered_plots});
    
    推荐文章