reactjs 如何使用onChange将状态值更新到文本区域?

mccptt67  于 2023-01-04  发布在  React
关注(0)|答案(1)|浏览(101)

目前正在学习一个稍旧的教程,但正在学习使用React 18 --尝试在notes应用程序中更新text area
看起来就像我打字时,一个字符出现,然后立即被自动删除
有人能证实我是不是漏掉了什么细节吗?
如果熟悉1:37:03时的项目,请参考:https://www.youtube.com/watch?v=6fM3ueN9nYM&t=377s

import React, {useState, useEffect} from 'react'

import notes from '../assets/data'
import { useParams } from 'react-router-dom';
import { Link } from 'react-router-dom'
import { ReactComponent as ArrowLeft } from '../assets/arrow-left.svg'

const NotePage = ( history ) => {
    const {id} = useParams();
    // let note = notes.find(note => note.id===Number(id))
    // console.log(id)
    let [note, setNote] = useState(null)

    useEffect(() => {
        getNote()
    }, [{id}])

    let getNote = async () => {
        let response = await fetch(`http://localhost:8000/notes/${id}`)
        let data = await response.json()
        setNote(data)
    }

    // let updateNote = async () => {
    //     await fetch(`http://localhost:8000/notes/${id}`, {
    //         method: 'PUT',
    //         headers: {
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify({...note, 'updated':new Date()})
    //     }) 
    // }

    // let handleSubmit = () => {
    //     updateNote()
    //     history.push('/')
    // }

  return (
    <div className="note">
        <div className="note-header">
            <h3>
                <Link to="/">
                    <ArrowLeft /*onClick={handleSubmit}*/ />
                </Link>
            </h3>
        </div>

        <textarea onChange={(e) => { 
            setNote({...note, 'body': e.target.value}) }} 
            value={note?.body}>
        </textarea>
    </div>
  )
}

export default NotePage
kqlmhetl

kqlmhetl1#

useEffect依赖项数组中的值不正确,导致每次在textArea中进行更改时都调用getNote。每次调用getNote时,它都会将便笺状态重置回getNote正在接收的状态。在您的情况下,可能是一个空白便笺
更改此内容:

useEffect(() => {
  getNote();
}, [{ id }]);

对此:

useEffect(() => {
  getNote();
}, [id]);

相关问题