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

Posted

技术标签:

【中文标题】仅更新 JSON 对象的一个​​值并使用 React Flux 保留旧的值【英文标题】:Update just one value of JSON object and keep the old ones with React Flux 【发布时间】:2020-09-01 13:29:51 【问题描述】:

我是 react/flux 的新手,我尝试练习,所以我尝试开发一个带有假后端(使用 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;

【问题讨论】:

【参考方案1】:

我确实是今天早些时候才知道的! 您可以在 reducer 中使用扩展运算符来保持所有对象相同并且只修改一个参数。希望这会有所帮助。

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;
  
;

【讨论】:

以上是关于仅更新 JSON 对象的一个​​值并使用 React Flux 保留旧的值的主要内容,如果未能解决你的问题,请参考以下文章

如何捕获更新列值并使用它?

如何更新json文件中的值并通过node.js保存

如何将 Jquery Autocomplete 设置为特定值并使用 JSON 对象的数据源显示它的标签

在对象的 json 数组中找到一个键值并返回另一个带有角度的键值

从 websocket 过滤 json 对象/值并打印到控制台日志

Json Response 需要更新 Javascript 值并替换全局初始全局值 - 需要解决解决方案