简体   繁体   English

React:无法通过将函数传递给更新它的子组件来更新父状态

[英]React: unable to update parent state by passing function to child component that updates it

I need to save form submission data to parents state from form component.我需要将表单提交数据从表单组件保存到父状态。

I can console.log the data from my save function on parent component but I can't seem to be able to change the state.我可以在父组件上使用 console.log 记录来自我的保存功能的数据,但我似乎无法更改状态。

Here is my attemp:这是我的尝试:

Parent Component:父组件:

import React, { Component } from "react";
import InputFormView from "./views/InputFormView";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formData: '',
    };
  }

  saveFormData = ( data ) => {

    let newState = Object.assign({}, this.state);
      newState.formData = data
      console.log("formData: ")
      console.log(newState) // I can see correct data here
    this.setState(newState)

    // this.setState({ formData : data }) // this also doesn't seem to update the state

    setTimeout(() => {
      console.log(this.state); // formData is empty
    }, 3000);
  };

  render() {
    return (
      <div className="App">
        <div className="container">
          <InputFormView saveFormData={this.saveFormData} />
        </div>
      </div>
    );
  }
}

export default App;

Child Component:子组件:

import React, { Component } from 'react';

class InputFormView extends Component {

    saveData = e => {
        e.preventDefault();
        ...
        this.props.saveFormData(JSON.stringify(values));
    }


    render() {

        return (
            <React.Fragment>
                ...
                <button onClick={this.saveData}>Save</button>
            </React.Fragment>
        );
    }
}

export default InputFormView;

I would like to avoid using Redux since this is a small application.我想避免使用 Redux,因为这是一个小应用程序。

How should I update the state of parent element from saveFormData function?我应该如何从 saveFormData 函数更新父元素的状态?

Try this:尝试这个:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formData: '',
    };
  }

  saveFormData = data => 
    this.setState(state => ({...state, formData: data}), ()=> console.log(this.state));

  render() {
    return (
      <div className="App">
        <div className="container">
          <InputFormView saveFormData={this.saveFormData} />
        </div>
      </div>
    );
  }

}
class InputFormView extends Component {

    constructor(props) {
      super(props);
      this.state = {
        myValue: 'hello'
      };
    }

    saveData = e => {
        e.preventDefault();
        this.props.saveFormData(this.state);
    }

    handleChange = e => this.setState({myValue: e.target.value});

    render() {
      const {myValue} = this.state;
        return (
            <React.Fragment>
                <input value={myValue} onChange={this.handleChange} />
                <button onClick={this.saveData}>Save</button>
            </React.Fragment>
        );
    }
}

A working version can be found at https://stackblitz.com/edit/react-parent-child-1可以在https://stackblitz.com/edit/react-parent-child-1找到工作版本

setState is async, so if you want to verify that it worked correctly, you can do so in its calllback function: setState是异步的,所以如果你想验证它是否正常工作,你可以在它的回调函数中这样做:

saveFormData = (data) => {

  this.setState({
    formData: data
  }, () => {
    console.log(this.state)
  });
};

It can be simplified by using previous state parameter in this.setState function.可以通过在this.setState函数中使用先前的 state 参数来简化它。

  saveFormData = ( data ) => {
    this.setState((prevState) => { ...prevState, formData: data});
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Swiper 子组件无法更新父级的 state - React Swiper child component unable to update parent's state 从子组件调用的反应父函数不更新状态? - React Parent Function Called from Child Component does not Update State? React,将状态从子组件传递给父组件 - React, passing state from a Child component to the Parent 在React中将状态从子组件更新为父组件 - Update the state from child to parent component in React 反应 - 我将 state 从子组件传递给父组件,但 state 值在一个更新周期内关闭 - React - I am passing state from a child to a parent component but the state value is off by one update cycle React中子组件更新时如何更新父组件 - How to Update the parent component when child component updates in React 反应父组件 state 更新但子不重新渲染 - React parent component state updates but child does not re-render 从父组件 React JS 调用 map function 时如何更新子组件的 state - How to update state of child component when it get called in map function from parent component React JS React/Redux - 从子组件更新父组件中的状态 - React/Redux - Update state in parent component from child component 当父组件更新时,React阻止子组件中的更改状态 - React prevent change state in child component when parent component update
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM