【问题标题】:Updating component to reflect changes in data?更新组件以反映数据的变化?
【发布时间】: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


    【解决方案1】:

    如果您在任何方法中使用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)}/> 
    

    【讨论】:

      【解决方案2】:

      在 Javascript 中,class methods are not bounded by default,这个 SO 答案谈到了 why is it like that?

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

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

      【讨论】:

      • 为什么this不是没有绑定的组件App?
      • 这就是javascript works的方式。默认情况下,类方法不受限制。
      【解决方案3】:

      尝试这样做

      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 上下文

      【讨论】:

        【解决方案4】:

        错误提示this.state未定义,您可能需要将函数this.onSubmitUpdateState作为箭头函数传递

        我不确定为什么当函数作为道具传递时这没有界限

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

        还有另一个答案是explains为什么会这样。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-31
          • 1970-01-01
          • 2013-01-02
          • 2016-11-15
          • 2021-12-10
          • 1970-01-01
          • 1970-01-01
          • 2011-05-24
          相关资源
          最近更新 更多