繁体   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