仅更新JSON对象的一个 值,并使用React Flux保留旧值

问题描述 投票:2回答:1

我是新来的反应者,我尝试练习,所以我尝试开发一个带有假后端(由FAKER创建的)的比萨店前端。我的问题是,我想更新我的JSON数据,但是我不知道该如何以及在何处执行此操作。重要的是,我只想更新JSON数据中的“ preparedAt”值,我想保留其他值(“ sequentialNumber”,“ id”,“ name”)。如何保留旧值,仅更新一个值?

例如,我要更新此内容:{“ sequentialNumber”:1,“ id”:61301,“ name”:“ molestiae”,“ preparedAt”:“ 2020-05-02T21:16:16.687Z”},对此:{“ sequentialNumber”:1,“ id”:61301,“ name”:“ molestiae”,“ preparedAt”:“ 2020-04-01”}

我的代码中也有一个搜索操作,但是效果很好。这是我的JSON文件和代码:

jsonFile.json

"preppizzas": [
    {
      "sequentialNumber": 1,
      "id": 61301,
      "name": "molestiae",
      "preparedAt": "2020-05-02T21:16:16.687Z"
    },
    {
      "sequentialNumber": 2,
      "id": 21349,
      "name": "impedit",
      "preparedAt": "2020-05-02T23:25:48.105Z"
    },
    {
      "sequentialNumber": 3,
      "id": 10235,
      "name": "beatae",
      "preparedAt": "2020-05-02T21:33:28.759Z"
    },
    {
      "sequentialNumber": 4,
      "id": 99688,
      "name": "dicta",
      "preparedAt": "2020-05-02T19:24:48.462Z"
    }
  ]

PizzaDispatcher.js

import {Dispatcher} from 'flux';
import axios from 'axios';
import Preparationstore from "./stores/PreparationStore";

class PizzaDispatcher extends Dispatcher{
    handleViewAction(action){
        this.dispatch({
            action : action
        });
    }
}

const dispatcher = new PizzaDispatcher();
dispatcher.register((payload)=>{
if(payload.action.actionType === 'PREPARATION_SEARCH') {
        if (payload.action.payload.id === "") {
            axios.get('/preppizzas').then((resp)=>{
                Preparationstore._preparations = resp.data.filter((preparation)=>{
                    return preparation.preparedAt.includes(payload.action.payload.preparedAt)
                });
                Preparationstore.emitChange();
            })
        }
        else {
            axios.get('/preppizzas').then((resp) => {
                Preparationstore._preparations = resp.data.filter((preparation) => {
                    return preparation.id == payload.action.payload.id;
                });
                Preparationstore.emitChange();
            })
        }
    }
    if(payload.action.actionType === 'PREPARATION_UPDATE'){
        if(payload.action.payload.id !==''){
            axios.put('/preppizzas/' + payload.action.payload.id,{
                preparedAt : payload.action.payload.preparedAt,
            }).then(resp=>{console.log(resp.data)}).catch(err => {console.log(err)
            });
        }
    }
});
export default dispatcher;

PreparationActions.js

import dispatcher from '../PizzaDispatcher'

class PreparationActions{
    search(id, preparedAt){
        dispatcher.handleViewAction({
            actionType : 'PREPARATION_SEARCH',
            payload : {
                id : id,
                preparedAt : preparedAt
            }
        });
    }
    update(preparedAt){
        dispatcher.handleViewAction({
            actionType : 'PREPARATION_UPDATE',
            payload : {
                preparedAt : preparedAt
            }
        });
    }
}

export default new PreparationActions;

PreparationStore.js

import EventEmitter from 'events'

class PreparationStore extends EventEmitter{
    _preparations = [];
    emitChange(){
        this.emit('Change');
    }

    addChangeListener(callback){
        this.on('Change', callback);
    }

    removeChangeListener(callback){
        this.removeListener('Change', callback);
    }
}
var Preparationstore = new PreparationStore();
export default Preparationstore;
import React from 'react';
import PreparationActions from "../../../../actions/PreparationActions";

PreparationsCRUD.js

class PreparationsCRUD extends React.Component{
    constructor(){
        super();
        this.state={
            id : "",
            preparedAt : ""
        }
    }

    render(){
        return(
            <div>
                <table>
                    <tr>
                        <td><input
                            type={"number"} min="0" placeholder="ID"
                            value={this.state.id}
                            onChange={(e)=>{
                                let st = this.state;
                                st.id = e.target.value;
                                this.setState(st);}
                            }
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    PreparationActions.search(this.state.id, this.state.preparedAt);
                                }
                            }}
                        /></td>
                    </tr>
                    <tr>
                        <td><input type={"text"} placeholder="Prepared at"
                                   value={this.state.preparedAt}
                                   onChange={(e)=>{
                                       let st = this.state;
                                       st.preparedAt = e.target.value;
                                       this.setState(st);
                                   }}
                        /></td>
                    </tr>
                    <tr>
                        <td
                            colSpan={2}>
                            <button
                                className="btn btn-info"
                                onClick={()=>{PreparationActions.search(this.state.id, this.state.preparedAt)
                                }}
                            >Search by ID
                            </button>
                            <button
                                className="btn btn-info"
                                onClick={()=>{
                                    PreparationActions.update(
                                        this.state.preparedAt,
                                    );window.location.reload();}}
                            >Update
                            </button>
                        </td>
                    </tr>
                </table>
            </div>
        );
    }
}

export default PreparationsCRUD;

PreparationsResults.js

import React from 'react';
import Preparationstore from "../../../../stores/PreparationStore";

class PreparationsResult extends React.Component{

    constructor(){
        super();
        this.state = {preparations : []};
        this._onChange = this._onChange.bind(this);
    }

    _onChange(){
        this.setState({preparations : Preparationstore._preparations})
    }

    componentDidMount(){
        Preparationstore.addChangeListener(this._onChange)
    }

    componentWillUnmount(){
        Preparationstore.removeChangeListener(this._onChange);
    }

    render(){
        return(
            <table className="table table-dark">
                <thead>
                <tr>
                    <td>Sequential number</td>
                    <td>Id</td>
                    <td>Name</td>
                    <td>Prepared at</td>
                </tr>
                </thead>
                <tbody>
                {
                    this.state.preparations.map((preparation)=>{
                        return(
                            <tr key={preparation.sequentialNumber}>
                                <td>{preparation.sequentialNumber}</td>
                                <td>{preparation.id}</td>
                                <td>{preparation.name}</td>
                                <td>{preparation.preparedAt}</td>
                            </tr>
                        );
                    })
                }
                </tbody>
            </table>
        );
    }
}
export default PreparationsResult;
javascript reactjs flux reactjs-flux refluxjs
1个回答
1
投票

我实际上是今天早些时候学到的!您可以在化简器中使用散布运算符,以使所有对象保持相同,并且仅修改一个参数。希望这会有所帮助。

const personReducer = (person, action) => {
  switch (action.type) {
    case 'INCREASE_AGE':
      return { ...person, age: person.age + 1 };
    case 'CHANGE_LASTNAME':
      return { ...person, lastname: action.payload.lastname };
    default:
      return person;
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.