为了账号安全,请及时绑定邮箱和手机立即绑定

更新组件以反映数据的变化?

更新组件以反映数据的变化?

扬帆大鱼 2021-12-02 14:51:40
尝试在“创建”组件中创建一个新注释发送了一个 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: ""    })  }
查看完整描述

3 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

如果您在任何方法中使用this.state,请使用箭头函数或绑定您的操作。


箭头函数:


  onSubmitUpdateState = (newNote) => {

    const oldState = [...this.state.notes]

    // Problem 2)

    this.setState({notes: [...oldState, newNote]});

  }

绑定方法: 创建构造函数并在构造函数中添加这一行


 this.onSubmitUpdateState = this.onSubmitUpdateState.bind(this)

没有构造函数


<Create updateState={this.onSubmitUpdateState.bind(this)}/> 


查看完整回答
反对 回复 2021-12-02
?
GCT1015

TA贡献1827条经验 获得超4个赞

在 Javascript 中,类方法在默认情况下不受限制,这个 SO 答案讨论了为什么会这样?


如果您不使用箭头函数,请确保bind()您的事件处理程序能够访问this.


<Create

  updateState={this.onSubmitUpdateState.bind(this)} // pass a binded handler

/>


查看完整回答
反对 回复 2021-12-02
?
青春有我

TA贡献1784条经验 获得超8个赞

尝试这样做


class App extends Component{

  state = {

    notes: []

  }


  componentDidMount(){

    fetch('http://localhost:3001/notes')

      .then(resp => resp.json())

      .then(data => this.setState({notes: data}))

  }




  onSubmitUpdateState = (newNote) => {   //change to arrow function//

    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;

箭头语法this为您处理绑定。或者您可以bind在构造函数中使用该函数。`


基本上箭头函数this在调用时会保留上下文


查看完整回答
反对 回复 2021-12-02
  • 3 回答
  • 0 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信