gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:05:26 26 4
gpt4 key购买 nike

我是 React 新手。我使用 Create-react-app 来创建我的应用程序。现在我尝试将其连接到我的后端 REST API。我已经成功地完成了这一点,只是为了获取和显示数据。现在我正在尝试通过表单更新数据。我正在关注 React 文档上的 Forms 页面。我之前遇到了一个问题,这是由于在我的状态下使用了一个对象,我认为我通过 this answer 解决了这个问题代码片段位于handleChange() 内的setState() 中。但我认为这可能与我当前的问题有关,即当我尝试在表单输入字段中键入任何内容时,表单输入字段不会更新。

这是我的 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;

我已通过 console.log 确认正在调用 handleChange。

最佳答案

尝试在 handleChange 中设置您的状态。

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

关于javascript - 为什么我不能用 React 更新我的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61237558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com