首页 > 解决方案 > 如何从 axios.get 返回的 useState 更新初始状态

问题描述

那里!好吧,我正在尝试为我的个人项目构建一个更新页面,在该页面上,我想拥有有关特定地点的所有信息。我将信息存储在 MongoDB 集群上并通过 axios.get 请求获取它。

让我更好地解释一下:

export default function({ history }) {

    window.data = {}
    const url = window.location.href.slice(-24)

    useEffect(() => {
        async function setParams() {
            const { data } = await api.get(`/spots/${url}`)

            console.log(data)
            window.data = data
            }
            setParams()
        }, [url]) 

        console.log(window.data)

//I'd like to put the window.data data inside of this 
//useStates, so I will display into the form inputs the 
//previous information to the user update it in the backend. 

        const [thumbnail, setThumbnail] = useState(null)<---
        const [company, setCompany] = useState('')<---
        const [price, setPrice] = useState('')<---
        const [techs, setTechs] = useState('')<---


    const preview = useMemo(() => {
        return thumbnail ? URL.createObjectURL(thumbnail) : null;
    }, [thumbnail])

    async function handleSubmit(event) {
        event.preventDefault()

        const data = new FormData()
        const user_id = localStorage.getItem('user')

        data.append('thumbnail', thumbnail)
        data.append('company', company)
        data.append('techs', techs)
        data.append('price', price)

        await api.put(`/updates/${url}`, data, { new: true })

        history.push('/dashboard')
    }
    return (
        <form onSubmit={handleSubmit}>
            <label 
            id='thumbnail' 
            style={{ backgroundImage: `url(${preview})` }}
            className={thumbnail ? 'has-thumbnail' : ''}
            >
                <input type='file' onChange={event => setThumbnail(event.target.files[0])}/>
                <img src={camera} alt='Select img' />
            </label>

            <label htmlFor="company">EMPRESA *</label>
            <input
                id="company"
                placeholder="Sua empresa"
                value={company}//I'd like to fill this inputs with the information that I got from the get request.
                onChange={event => setCompany(event.target.value)}
            />

            <label htmlFor="company">TECNOLOGIAS *<span>(separadas por vírgula)</span></label>
            <input
                id="techs"
                placeholder="Tenologias utilizadas"
                value={techs}
                onChange={event => setTechs(event.target.value)}
            />

            <label htmlFor="company">PREÇO *</label>
            <input
                id="price"
                placeholder="Valor por dia"
                value={price}
                onChange={event => setPrice(event.target.value)}
            />

            <button type='submit' className='btn'>Cadastrar</button>
        </form>
    )
}

我所知道的是,我需要在收到请求后渲染页面或至少 useStates。我已经尝试了很多方法来做到这一点,但没有任何效果。

我应该把所有东西都放在一个类中并使用 Async/Await 吗?我不知道如何将此代码更改为它。

标签: javascriptnode.jsreactjsreact-routeraxios

解决方案


推荐阅读