Axios + React(Next.js),发布请求丢失上下文/状态的跟踪

pkmbmrz7  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(186)

我已经挠头好几个小时了,这个窃听器对我来说没有任何意义。
类似于this解决的问题,react上下文和状态在请求完成后丢失,唯一的问题是我的所有函数都已经绑定。
下面的代码应该返回一个图像url,并在每次单击按钮时将其添加到“image”数组状态中。但不起作用的是,“image”数组状态的内容在axios promise中被神奇地遗忘了,这意味着所有先前的图像都丢失了,只有请求返回的图像最终会出现在该状态中。
我以前从来没有遇到过这样的事情,我觉得我一定是错过了我犯下的某个愚蠢的错误。有人知道这是怎么回事吗?
谢谢你的好意,

// Added
const RANDOM_PROMPTS = [
    'a whale flying in the sky',
    'a skeleton dancing',
    'a sunflower growing in a field'
]

export default function Home() {

    const [prompt, setPrompt] = useState('')
    const [images, setImages] = useState([])

    // Added
    useEffect(() => {
        randomPrompt()
    }, []) 

    const handleSubmit = event => {
        event.preventDefault()
        event.stopPropagation()

        axios.post('http://localhost:3000/v1/generate', {prompt})
        .then(res => {
            res.data && add(res.data.url)
        })
    }

    const add = (url) => {
        // images state is always [] here
        console.log(images)
        setImages([...images, url])
    }

    // Added
    const randomPrompt = () => {
        const prompt = RANDOM_PROMPTS.shift()

        setPrompt(`a painting of ${prompt}, by Paul Delvaux`)
    }

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input type="text" value={prompt} onChange={event => setPrompt(event.target.value)}/>
                <button type="submit">Draw</button>
            </form>
        </div>
    )
}
6qqygrtg

6qqygrtg1#

您是否尝试使函数handleSubmit成为异步函数?

const handleSubmit = async (event) => {
        event.preventDefault()
        event.stopPropagation()

        const {data} = await axios.post('http://localhost:3000/v1/generate', 
        {prompt},{
         validateStatus: (status) => status === 201,
        })
        if(!!data && !!data.url) {
          add(data.url)
        }
    }

我希望你能像这样修改你的功能:

const add = (url) => {
        console.log(images)
        setImages((prevState) => [...prevState, url])
    }

我的意见是在这个过程中,你可能会失去你的React状态的背景。

9udxz4iz

9udxz4iz2#

随机提示不应该对Axios请求有任何影响,你正在对不同的useEffect()依赖。请尝试我的代码下面,我试图做我在我的评论中建议。

const RANDOM_PROMPTS = [
    'a whale flying in the sky',
    'a skeleton dancing',
    'a sunflower growing in a field'
]

export default function Home() {

    const [prompt, setPrompt] = useState('')
    const [images, setImages] = useState([])
    const [initiateRequest, setInitiateRequest] = useState(false)

    // Added
    useEffect(() => {
        randomPrompt()
    }, []) 

async function fetchData() {
    let response = axios.post('http://localhost:3000/v1/generate', {prompt})
        .then(res => {
            res.data && add(res.data.url)
        })
  }
    useEffect(() => {
        fetchData()
    }, [initiateRequest]) 

    const handleSubmit = event => {
        event.preventDefault()
        event.stopPropagation()
        setInitiateRequest(true)
    }

    const add = (url) => {
        // images state is always [] here
        console.log(images)
        setImages([...images, url])
    }

    // Added
    const randomPrompt = () => {
        const prompt = RANDOM_PROMPTS.shift()

        setPrompt(`a painting of ${prompt}, by Paul Delvaux`)
    }

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input type="text" value={prompt} onChange={event => setPrompt(event.target.value)}/>
                <button type="submit">Draw</button>
            </form>
        </div>
    )
}

相关问题