React CRUD更新方法是使用React Context的最佳实践唯一来源吗?

问题描述

因此,我一直在尝试通过使更新方法直接更改状态并在文本字段中读取状态,来使状态“真相”在我的工作中发挥作用。除了编写更多代码之外,此方法是否没有其他缺点?还是通过将update字段设置为TagTable组件内的单独状态并将onSubmit与上下文状态合并,通常不会带来安全隐患。

这些类型的更新方法的最佳实践或一般规则是什么?


TagContextProvider

请注意update(),handleChange()和resetTag(),因为它们与问题有关。向下滚动以查看表格组件。
public String scanAasha(String aashacomand){
   aasha=aashacomand;
   mAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mAdapter!= null) {
      mAdapter.startdiscovery();
      aashadiscovery();
   }
     if (mBluetoothChatServiceaasha.maasha.contains("B_")) {
       String a[] = mBluetoothChatServiceaasha.maasha.split("_");
       return a[1] + " " + a[2];
     }
     if (mBluetoothChatServiceaasha.maasha.contains("O_")) {
       String a[] = mBluetoothChatServiceaasha.maasha.split("_");
       return a[1] + " " + a[2];
     }
     if (mBluetoothChatServiceaasha.maasha.contains("T_")) {
       String a[] = mBluetoothChatServiceaasha.maasha.split("_");
       return a[2];
     }
    return aashacomand;
  }

  
public void aashadiscovery() {
int hasPermission = ActivityCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
registerReceiver(searchAasha,intentFilteractions());
mAdapter.startdiscovery();
return;
}
else{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION},AASHA_REQUEST_COARSE_LOCATION_PERMISSIONS);
registerReceiver(searchAasha,intentFilteractions());
mAdapter.startdiscovery();
return;
}
}
  
private broadcastReceiver searchAasha = new broadcastReceiver() {
@Override
public void onReceive(Context context,Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();
// ??????????????????????
for (int i = 0; i < lstName.length; i++) {
String keyName = lstName[i].toString();
Log.e(keyName,String.valueOf(b.get(keyName)));
}

if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName()==null) {
return;
}
if (device.getName().contains("SPP")) {
mBluetoothChatServiceaasha.start();
mBluetoothChatServiceaasha.connect(device);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Todo Auto-generated catch block
e.printstacktrace();
}
}
}
}
};

TagTable

请注意setEdit(),onEditSubmit()和onEditClose()
import React,{createContext} from 'react';
import {withAlertContext} from './AlertContext';
import axios from 'axios';

export const NewTagContext = createContext();

class NewTagContextProvider extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tags:         null,processing:   false,read:         this.read.bind(this),create:       this.create.bind(this),delete:       this.delete.bind(this),update:       this.update.bind(this),resetTag:     this.resetTag.bind(this),handleChange: this.handleChange.bind(this),};
    };


    render() {
        return (
            <NewTagContext.Provider value={{
                ...this.state,}}>
                {this.props.children}
            </NewTagContext.Provider>
        );
    }

    /**
     * Takes an array of tags and finds the highest number of the id's,adds +1 to it and returns that
     * @param {[]} [array=this.state.tags] - array of tags
     * @returns {number} - generated id
     */
    findHighestId(array = this.state.tags) {
        let max = 0;
        for (let i = 0,len = array.length; i < len; i++) {
            if (array[i].id > max) max = array[i].id;
        }
        return max + 1;
    }

    /**
     * EDIT TAG HANDLER
     * @param {object} index - index of tag to be updated
     * @param {object} e - event
     */
    handleChange(index,e) {
        // find and replace
        const TAGS_copY = this.state.tags.slice();
        TAGS_copY[index].name = e.target.value;
        this.setState({tags: TAGS_copY});
    }

    /**
     * @param originalTag - the tag before the user starts typing in the text field.
     */
    resetTag(originalTag) {
        //copy state
        const TAGS_copY = this.state.tags.slice();
        //find tag in copy
        let TAG_copY = TAGS_copY.find(tag => tag.id === originalTag.id);
        //replace new name to the old name
        TAG_copY.name = originalTag.name;
        //overwrite the state
        this.setState({
            tags: TAGS_copY,});
    }

    /**
     * @param {object} createdTag - a new tag created by the user
     * @param {string} createdTag.name - name of the created tag
     */
    async create(createdTag) {
        // INITIATE
        if (this.state.processing) return;
        else this.setState({processing: true});

        // PREParaTION START
        const INITIAL_TAGS = this.state.tags.slice();
        const RESET = () => this.setState({tags: INITIAL_TAGS,processing: false});
        const {alertContext} = this.props;
        // PREParaTION END

        if (INITIAL_TAGS)
            try {
                // CLIENT OPTIMIZATION START
                const NEW_TAG_FROM_CLIENT_WITH_ID = {...createdTag,id: this.findHighestId()};
                this.setState({tags: this.state.tags.concat(NEW_TAG_FROM_CLIENT_WITH_ID)});
                // CLIENT OPTIMIZATION END

                // REQUEST START
                const r = await axios.post('/api/tag/create',NEW_TAG_FROM_CLIENT_WITH_ID);
                const {alert: ALERT,tag: NEW_TAG_FROM_SERVER} = r.data;
                // REQUEST END

                // PROCESS ALERT
                alertContext.setAlert(ALERT);

                // SERVER SIDE ERROR CATCHER START
                if (ALERT.level !== 'success') {
                    RESET();
                    return;
                }
                // SERVER SIDE ERROR CATCHER END

                // IF SERVER SIDE IS SUCCESSFUL

                // CHECK IF SERVER DATA MATCHES CLIENT DATA START
                if (NEW_TAG_FROM_SERVER.id !== NEW_TAG_FROM_CLIENT_WITH_ID.id) {
                    // CORRECT THE DATA
                    this.setState((state) => {
                        const TAGS = state.tags.slice();
                        const TAG = TAGS.find(tag => tag.id === NEW_TAG_FROM_CLIENT_WITH_ID.id);
                        TAG.id = NEW_TAG_FROM_SERVER.id;
                        return {tags: TAGS,processing: false};
                    });
                }
                // CHECK IF SERVER DATA MATCHES CLIENT DATA END

                else {
                    this.setState({processing: false});
                }

            } catch (e) {
                alertContext.setAlert({
                    text:  [
                        e,'Something went wrong while trying to create a tag.','Check your internet connection to make sure you didn\'t lose it or perhaps our servers may be down for maintenance.',],level: 'error',});
                RESET();
            }
    }

    /**
     * Gets all tags from the database
     * @returns {Promise<void>}
     */
    async read() {
        // INITIATE
        if (this.state.processing) return;
        else this.setState({processing: true});

        // PREParaTION START
        const {alertContext} = this.props;
        // PREParaTION END

        try {
            //REQUEST
            const r = await axios.get('/api/tag/read');
            //HANDLE REQUEST
            this.setState({tags: r.data,processing: false});
        } catch (e) {
            //CLIENT SIDE ERROR START
            alertContext.setAlert({
                text:  [
                    e,});
            this.setState({tags: [],processing: false});
            //CLIENT SIDE ERROR END
        }
    }

    /**
     * Updates a tag by replacing the name key of the tag object
     * @param {object} originalTag
     * @param {number} originalTag.id
     * @param {string} originalTag.name
     * @returns {Promise<void>}
     */
    async update(originalTag) {
        // PREParaTION START
        const INITIAL_TAGS = this.state.tags.slice();
        const RESET = () => {this.setState({tags: INITIAL_TAGS,processing: false});};
        const {alertContext} = this.props;
        // PREParaTION END

        try {
            // UPDATE CLIENT START
            const TAG_copY = INITIAL_TAGS.slice().find(tag => tag.id === originalTag.id);
            if (TAG_copY.name === originalTag.name) {
                alertContext.setAlert({text: 'There was no change to the tag.',level: 'info'});
                this.setState({processing: false});
                return;
            }
            // UPDATE CLIENT END

            // REQUEST START
            const r = await axios.put('/api/tag/update/' + originalTag.id,TAG_copY);
            const {alert: ALERT} = r.data;
            alertContext.setAlert(ALERT);
            // REQUEST END

            // SERVER SIDE ERROR START
            if (ALERT.level !== 'success')
                RESET();
            else
                this.setState({processing: false});
            // SERVER SIDE ERROR END
        } catch (e) {
            // CLIENT SIDE ERROR START
            alertContext.setAlert({
                text:  [
                    e,'Something went wrong while trying to update the tag.',});
            RESET();
            // CLIENT SIDE ERROR END
        }
    }

    /**
     * Removes a tag from the state,in case it Could not be removed from the database: undo
     * @param {object} tag
     * @param {number} tag.id
     * @param {string} tag.name
     */
    async delete(tag) {
        // INITIATE
        if (this.state.processing) return;
        else this.setState({processing: true});

        //PREParaTION START
        const INITIAL_TAGS = this.state.tags.slice();
        const RESET = () => {this.setState({tags: INITIAL_TAGS,processing: false});};
        const {alertContext} = this.props;
        //PREParaTION END

        try {
            // DELETE ON CLIENT SIDE START
            const FILTERED_TAGS = INITIAL_TAGS.slice().filter(initialTag => initialTag.id !== tag.id);
            this.setState({tags: FILTERED_TAGS});
            // DELETE ON CLIENT SIDE END

            // REQUEST START
            const r = await axios.delete('/api/tag/delete/' + tag.id);
            const {alert: ALERT} = r.data;
            // REQUEST END

            // PROCESS ALERT
            alertContext.setAlert(ALERT);

            // SERVER SIDE ERROR START
            if (ALERT.level !== 'success')
                RESET();
            else
                this.setState({processing: false});
            // SERVER SIDE ERROR END
        } catch (e) {
            alertContext.setAlert({
                text:  [
                    e,'Something went wrong while trying to delete the tag.',});
            RESET();
        }
    }
}

export default withAlertContext(NewTagContextProvider);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...