簡體   English   中英

React Redux-更新狀態數組中的子級

[英]React Redux - update child in state array

所以我在Redux存儲中有一個稱為currentAccount的對象。 它具有一個稱為“ groups的子數組,該子數組具有一個名為“ tasks的子數組。

現在,我差不多可以通過以下方式輕松地在Angular中真正更新一項任務:

function updateTask(task){
   http.post('xyz/updateTask', function(updatedTask){
        task = updatedTask;
   });
}

...就可以了。

在React中,我可以將數據分派到actions ,然后使用Axios將其發布到API,但是然后...如何查找和更新舊任務?

我可以:

  • 獲取服務器以再次返回整個currentAccount對象,然后將其轉換為JSON字符串並返回(強制Redux重新呈現整個樹),
  • ...或在forEach中執行forEach以通過其ID查找任務,然后將其替換(盡管我不確定Redux是否會接受更改)

但是,這兩者都讓我感到非常瘋狂。 有沒有更簡單的方法,或者僅僅是React的工作方式?

抱歉,這是一個愚蠢的問題,我不太確定該怎么說,哈哈。

收到來自http呼叫的響應后,請分派更新商店的操作。 您將需要訪問組件中的分派,因此您將使用mapDispatchToProps提供功能。

這是創作者Dan Abramov編寫的 Redux入門教程。

此代碼示例應為您提供幫助。

// I'm using this stateless functional component to
// render the presentational view
const Task = ({ label, info }) => (
    <div className="task">
        <h3{ label }</h3>
        <p{ info }</p>
    </div>
);

// this is the class that receives props from connect
// and where we render our tasks from
class Tasks extends PureComponent {

    // once your component is mounted, get your
    // http data and then disptach update action
    componentDidMount() {
        // using axios here but you can use any http library
        axios.post( "/some_url", task )
            .then( ( response ) => {

                // get update provided by mapDispatchToProps
                // and use it to update tasks with response.data
                const { update } = this.props;
                update( response.data );
            })
            .catch( ( error ) ) => {
                // handle errors
            }
    }

    render() {
        // destructure tasks from props
        const { tasks } = this.props;

        // render tasks from tasks and pass along props
        // if there are no tasks in the store, return a loading indicator
        return (
            <div className="tasks">
                {
                    tasks ? tasks.map(( task ) => {
                        return <Task
                            label={ task.label }
                            info={ task.info }
                        />
                    }) :
                    <div className="loading">Loading...</div>
                }
            </div>
        );
    }
}

// this will provide the Tasks component with props.task
const mapStateToProps = ( state ) => {
    return {
        tasks: state.tasks
    }
}

// this will provide the Tasks component with props.update
const mapDispatchToProps = ( dispatch ) => {
    return {
        update: ( tasks ) => {
            dispatch({
                type: "UPDATE_TASKS",
                tasks
            });
        }
    }
}

// this connects Task to the store giving it props according to your
// mapStateToProps and mapDispatchToProps functions
export default Task = connect( mapStateToProps, mapDispatchToProps )( Task );

您將需要一個處理"UPDATE_TASK"操作的減速器。 精簡器更新商店,並考慮到組件已連接,它將接收具有更新的商店值的新道具,並且任務將在DOM中更新。

編輯:為了解決減速器,這是一個附加的示例。

import { combineReducers } from "redux";

const tasks = ( state = [], action ) => {
  switch( action.type ) {
    case "UPDATE_TASKS":
      // this will make state.tasks = action.tasks which
      // you dispatched from your .then method of the http call
      return action.tasks;
    default:
      return state;
  }
};

const other = ( state = {}, action ) => {
  ...
}

const combinedReducers = combineReducers({
  tasks,
  other
});

const store = createStore(
    combinedReducers/*,
    persisted state,
    enhancers*/
);    

/*

  The above setup will produce an initial state tree as follows:

  {
    tasks: [ ],
    other: { }
  }

  After your http call, when you dispatch the action with the tasks in
  the response, your state would look like

  {
    tasks: [ ...tasks you updated ],
    other: { }
  }

*/

如果還有其他人陷入困境,我想我已經解決了。

我只是傳遞任務父級的所有索引,然后使用'dotPoints'設置狀態,如下所示:

dotProp.set(state, `currentProject.groups.${action.groupIndex}.tasks.${action.taskIndex}`, action.task);

到目前為止,似乎是一個相當簡潔的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM