简体   繁体   English

从promise.then在子级中触发父级中的setState函数

[英]Trigger setState function in parent from promise.then in child

I am trying to find a solution to setState from a parent within child promise . 我正在尝试从child promiseparent找到setState的解决方案。

The parent component is parent component

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      transition: false
    };
  }

  handleTransition = () => {
    this.setState(state => ({ transition: !state.transition }));
  };

  render() {
    return <Child handleTransition={this.handleTransition} />;
  }
}

of which this.props.handleTransition is to be triggered from a child component as 其中this.props.handleTransition将从child component触发为

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onSubmit = event => {
    firebase
      .doCreateUserWithEmailAndPassword(email, password)
      .then(() => {
        // Trigger this.props.handleTransition here
      })
      ...

Where this.props.handleTransition is wanting to be triggered with then of onSubmit this.props.handleTransition是想与被触发thenonSubmit

Please let me know if you require more detail? 如果您需要更多详细信息,请告诉我? I would prefer not to use a library or package to achieve this but if it makes life easier I may consider. 我不希望使用库或程序包来实现此目的,但是如果它使生活更轻松,我可能会考虑。 Redux is likely the best option but I would prefer not to unless necessary. Redux可能是最好的选择,但除非有必要,否则我不希望这样做。

Note: this.props.handleTransition(); 注意: this.props.handleTransition(); does the job but esLint returns an error of Must use destructuring props assignmenteslint(react/destructuring-assignment) and I am considering that this method is not the correct method. 做这项工作,但esLint返回错误Must use destructuring props assignmenteslint(react/destructuring-assignment) ,我正在考虑此方法不是正确的方法。

// --- parent.js

import React, { Component, Fragment } from "react";
import { ChildComponent } from './containers/child'

class ParentContainer extends Component {

  handleUpdate = () => {
    // whatever you want to do here
  }

  render(){
    return (
      <Fragment>
        <ChildComponent onUpdate={this.handleUpdate} />
      </Fragment>
    );
  }
}

export default ParentContainer;

// --- child.js

import React, { Component, Fragment } from "react";

export class ChildComponent extends Component {

  this.someAsyncFunction = () => {
    fetch('/just/for/example')
    .then(res => 
        // Do whatever you need here, then hit your function on parent by bubbling the request up the chain
        this.props.onUpdate();
      ) 
  }

  render(){
     return (
      // whatever you want to do with this data
    );
  }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM