reactjs - 如何在 React js 中预填充表单 | 无法预先填写 react js 中的字段以进行编辑?
问题描述
1)我即将编辑该字段,以便我可以看到我之前写的内容并对其进行编辑,我知道有一些答案类似的答案,但我无法弄清楚我的项目中发生了什么。
我的EditCategory.js看起来像
import React, { Component } from 'react'
import axios from 'axios'
export default class EditCategory extends Component {
state = {
name : "",
}
componentDidMount() {
//console.log(' cdm working ? ', this.props.match.params._id) //YES
this.props.getSingleCategory(this.props.match.params._id);
}
onInputChange = (e) => {
this.setState({name: e.target.value }) //looks for name
}
onFormSubmit = (e) => {
e.preventDefault();
const category = {
_id : this.props.match.params._id,
name : this.state.name
}
axios.put(`http://localhost:5000/api/genres/${category._id}`, category)
.catch( error => console.log("error occured ")) //set error to the state var and ...
window.location = "/categories"
}
render() {
const { category, isLoading } = this.props;
if(isLoading || !category ) {
return <h3>Category is not loaded properly.</h3>
}
return (
<div className="container">
<h2>Update CATEGORY </h2>
<form onSubmit = { this.onFormSubmit }>
<div className="form-group">
<label htmlFor="name">Category Name:</label>
<input type="text" required className="form-control" id="name"
onChange={this.onInputChange}
//value={this.state.name }
value={category.name}
/>
</div>
<button type="submit" className="btn btn-primary">Update Category</button>
</form>
</div>
)
}}
我的App.js是 import ....
state = {
books : [],
categories : [],
book : {},
category : {}, //consider this
isLoading : false,
}
//only id is unique
getSingleCategory = async (categoryId) => {
//console.log("app.js book id " , bookId)
this.setState({isLoading : true})
const res = await axios.get(`http://localhost:5000/api/genres/${categoryId}`)
//console.log(res.data)
this.setState({ category : res.data, isLoading : false})
}
.
.
.
<Route
exact path={ "/cateogories/:_id/" }
render={ (props) => (
<EditCategory {...props }
category={category}
loadiing = {isLoading}
getSingleCategory ={this.getSingleCategory}
/>
)
}
/>
当我单击正确定义的链接并更新字段时,它可以工作,但加载时字段为空,但会正确更新所选项目。
我应该在 value={what goes here 中写什么?} 以便它预先填充数据。
解决方案
推荐阅读
- spring - 发生错误时可重复 KStream
- sql-server - 当单元格之一必须接受超过 255 个字符的值时,如何从 SQL Server 在 Excel 中加载数据
- java - 如何扫描和响应用户的输入?
- react-native - 任何带有初始向量的 AES 128 加密的本机库?
- amazon-ec2 - 限制对远程端口的访问
- pandas - 熊猫系列右连接的定义是什么?
- python - Python pxssh 期望模式与“#”不匹配
- events - 关于 EventSourcing、微服务、CQRS 的说明
- javascript - 在 node.js 中使用 alasql 加入两个包含 where 子句的 select 语句
- ios - 是否可以同时在 react-native 中使用前置和后置摄像头?