首页 > 解决方案 > 如何在 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 中写什么?} 以便它预先填充数据。

标签: reactjsreact-routerjsx

解决方案


推荐阅读