尝试在“创建”组件中创建一个新注释发送了一个 POST 请求并将其添加到数据库中。现在我需要将更改反映在“App”组件的状态中。
解决方案:在将 Note (Create Comp) 提交到数据库时,将对象的副本发送到 App.js,在那里我们更新 state 中的 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: ""
})
}
慕姐4208626
GCT1015
青春有我
相关分类