javascript - 如何从 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 吗?我不知道如何将此代码更改为它。
解决方案
推荐阅读
- jupyter-notebook - ipywidgets 在交互之前不显示情节
- java - Java Sudoku 帮助:如何将我的数独字符串转换为 2d int?
- amazon-cloudformation - 使用 Cloudformation 的 EC2-RDS 设置不起作用
- angular - ngx translate angular 7 如何翻译动态数据来自不同的 API
- r - R vglm() 错误:警告(“出现数字 0 或 1 的拟合概率”)
- javascript - NODE.js MongoDB 有不同的客户端获取多个值
- c - POSIX AIO 的 aio_write() 和 lio_listio() 在写操作中不能正常工作
- solr - 如何比较 solr json 中的日期
- javascript - 能够使用 Flutter 和 dart 语言在 MainModule (ScopedModel) 中连接多个模型
- javascript - 像管理屏幕一样的 CRUD UI