简体   繁体   English

javascript - 为什么我不能用 React 更新我的表单字段

[英]javascript - why can't I update my form fields with React

I'm new to React.我是反应新手。 I have used Create-react-app to create my app.我使用 Create-react-app 来创建我的应用程序。 Now I'm trying to connect it to my back-end REST APIs.现在我正在尝试将它连接到我的后端 REST API。 I have done that successfully for simply getting and displaying data.我已经成功地完成了简单的获取和显示数据。 Now I'm trying to enable updating data via a form.现在我正在尝试通过表单启用更新数据。 I'm following the Forms page on the React docs.我正在关注 React 文档上的 Forms 页面。 I had an earlier problem which was due to using an object in my state, which I thought I solved via this answer with the snippet in the setState() inside handleChange().我有一个较早的问题,这是由于在我的 state 中使用了 object,我认为我通过这个答案解决了这个问题,其中包含 handleChange() 中的 setState() 片段。 But I think that may have something to do with my current problem, which is that the form input fields don't update when I try to type anything in them.但我认为这可能与我当前的问题有关,即当我尝试在其中输入任何内容时,表单输入字段不会更新。

Here's my js page:这是我的js页面:

import React, { Component } from 'react';
import { Container } from 'reactstrap';
import AppNavbar from './AppNavbar';

class TradeConfig extends Component {

  constructor(props) {
    super(props);
    this.state = {tradeConfig: {}, isLoading: true};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    console.log("handleChange : " + event);
    const target = event.target;
    const value = target.value;
    const name = target.name;

    this.setState(oldState => {
      return {
        foo: Object.assign({}, oldState.tradeConfig, {[name]: value})
      }
    });
  }

  handleSubmit(event) {
      alert('A form was submitted: ' + this.state.tradeConfig);
      event.preventDefault();

      fetch(process.env.REACT_APP_API_URL+'/api/config', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(this.state.tradeConfig)
      }).then(() => {
          fetch(process.env.REACT_APP_API_URL+'/api/config')
              .then(response => response.json())
              .then(data => this.setState({tradeConfig: data, isLoading: false}));
      });
  }

  componentDidMount() {
    this.setState({isLoading: true});

    fetch(process.env.REACT_APP_API_URL+'/api/config')
      .then(response => response.json())
      .then(data => this.setState({tradeConfig: data, isLoading: false}));
  }


  render() {
    const {tradeConfig, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <h3>Trade Config</h3>

            <form onSubmit={this.handleSubmit}>
                <label>Position Size: </label>
                    <input
                        name="positionSize"
                        type="number"
                        value={this.state.tradeConfig.positionSize}
                        onChange={this.handleChange} />
                <br/>
                <label>Actively Trading:
                    <input
                        name="activelyTrading"
                        type="boolean"
                        value={this.state.tradeConfig.activelyTrading}
                        onChange={this.handleChange} />
                </label>
                <br/>
                <input type="submit" value="Submit" />
            </form>

        </Container>
      </div>
    );
  }
}

export default TradeConfig;

I have confirmed via console.log that the handleChange is being called.我已通过 console.log 确认正在调用 handleChange。

Try setting your state like this in handleChange .尝试在 handleChange 中像这样设置您的handleChange

this.setState({
  tradeConfig:{
      ...this.state.tradeConfig,
      [name]:value
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM