【发布时间】:2019-10-24 07:53:49
【问题描述】:
试图在“创建”组件中创建一个新注释发送了一个 POST 请求并将其添加到数据库中。现在我需要将更改反映在“App”组件的状态中。
解决方案:在向数据库提交 Note (Create Comp) 时,会将对象的副本发送到 App.js,我们会在其中更新状态中的 note 属性,以便它反映数据库中的更改。
问题:出现一些错误,问题行已在代码中标记。
class App extends Component{
state = {
notes: []
}
componentDidMount(){
fetch('http://localhost:3001/notes')
.then(resp => resp.json())
.then(data => this.setState({notes: data}))
}
onSubmitUpdateState(newNote){
const oldState = [...this.state.notes]
// Problem 2)
this.setState({notes: [...oldState, newNote]});
}
render(){
return(
<div className="App">
<Notes notes={this.state.notes}/>
<Create updateState={this.onSubmitUpdateState}/>
</div>
)
}
}
export default App;
import React, { Component } from 'react';
import classes from './Create.module.css';
class Create extends Component{
state= {
title: "",
body: ""
}
onChange = (e)=>{
this.setState({[e.target.name]: e.target.value})
}
handleSubmit = (e)=>{
e.preventDefault();
const post = {
title: this.state.title,
body: this.state.body
}
// Problem 1
fetch('http://localhost:3001/notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
.then(res => res.json())
.then(data => this.props.updateState(data))
this.setState({
title: "",
body: ""
})
}
render(){
return (
<div className={classes.CreateContainer}>
<div className={classes.Create}>
<h1>Create</h1>
<form onSubmit={this.handleSubmit}>
<label>Title:</label><br/>
<input type="text" name="title" onChange={this.onChange} value={this.state.title}></input><br/>
<label>Body:</label><br/>
<textarea row="8" col="50" name="body" onChange={this.onChange} value={this.state.body}></textarea><br/>
<input type="submit" value="Submit"></input>
</form>
</div>
</div>
)
}
}
export default Create;
【问题讨论】:
标签: javascript reactjs http state