簡體   English   中英

反應 - .setState 部分不起作用

[英]React - .setState is partially not working

我需要幫助更新 React 中的狀態。 我正在使用 React 制作加密/解密表單。 此 EncryptForm 在 App.js 中呈現。 我想要做的是監聽onSubmit函數並更新 isSubmitted 狀態,然后在“轉換”按鈕下呈現decipher值。

我的問題是為什么.setStatehandleChange方法中有效,但在handleSubmit方法中handleSubmit 我錯過了什么? encryptMessagedecryptMessage方法工作正常。)

這是 EncryptForm 組件代碼。

import React, { Component } from 'react'
import crypto from 'crypto'

class EncryptForm extends Component {
    state = {
        userInput: '',
        isSubmitted: false,
        decipher: ''
    }

    encryptMessage(input, key) {
        // Initialization Vector - 16 bytes
        const iv = new Buffer(crypto.randomBytes(16), 'utf8')
        const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
        let encoded = cipher.update(input, 'utf8', 'base64')
        encoded += cipher.final('base64')
        return [encoded, iv, cipher.getAuthTag()]
    }

    decryptMessage(key, encoded, iv, authTag) {
        const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)
        decipher.setAuthTag(authTag)
        let text = decipher.update(encoded, 'base64', 'utf8')
        text += decipher.final('utf8')
        return text
    }

    /*
        Non-encryption methods
    */
    handleSubmit = event => {
        event.preventDefault()
        const KEY = new Buffer(crypto.randomBytes(32), 'utf8')
        const [encrypted, iv, authTag] = this.encryptMessage(this.state.userInput, KEY)
        const decrypted = this.decryptMessage(KEY, encrypted, iv, authTag)
        const newState = {
            ...this.state,
            isSubmitted: true,
            decipher: decrypted
        }

        // THIS IS NOW UPDATING THE STATE :(
        this.setState({ newState })
    }

    handleChange = event => {
        this.setState({
            [event.target.name]: event.target.value,
        })
    }

    render() {
        const { userInput, isSubmitted, decipher } = this.state
        const isInvalid = userInput === ''
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    type='text'
                    name='userInput'
                    placeholder='Encrypt this text...'
                    onChange={this.handleChange}
                />
                <button disabled={isInvalid} type='submit'>Convert</button>
                {isSubmitted && <p>{decipher.value}</p>}
            </form>
        )
    }
}

export default EncryptForm

謝謝!

您在handleSubmit錯誤地設置了狀態。 newState是整個狀態對象,因此像this.setState({ newState })一樣設置它不會更新整個狀態,而是創建一個名為newState的新鍵並將其設置為您期望的狀態。 結果是這樣的:

state = {
  ...previous_state,
  newState: {
    ...this.state,
    isSubmitted: true,
    decipher: decrypted
  },
}

相反,您可以執行以下操作來正確更新:

// desctructure so it overwrites each key
this.setState({ ...newState });

// pass the non-nested object
this.setState(newState);

或者首選方法是僅更新必要的密鑰。 this.setState與給定的對象和先前的狀態進行淺層合並。 所以你不需要做{...this.state} (實際上這是不鼓勵的)。

這是最簡潔准確的方法:

this.setState({ isSubmitted: true, decipher: decrypted });

暫無
暫無

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

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