代码之家  ›  专栏  ›  技术社区  ›  Darren

从promise.then到child在父级中触发setState函数

  •  0
  • Darren  · 技术社区  · 7 年前

    我正试图找到解决问题的办法 setState parent child promise .

    父母亲 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} />;
      }
    }
    

    this.props.handleTransition 将从 小孩 组成部分

    class Child extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
    
      onSubmit = event => {
        firebase
          .doCreateUserWithEmailAndPassword(email, password)
          .then(() => {
            // Trigger this.props.handleTransition here
          })
          ...
    

    哪里 这个。道具。手柄转换 是想被触发的 then 属于 onSubmit

    如果你需要更多的细节,请告诉我?我宁愿不使用图书馆或包来实现这一点,但如果它使生活更容易,我可以考虑。Redux可能是最好的选择,但我宁愿不这样做,除非必要。

    this.props.handleTransition(); 做这项工作但是 esLint 返回的错误为 Must use destructuring props assignmenteslint(react/destructuring-assignment) 我认为这种方法不是正确的方法。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dadsquatch    7 年前
    // --- 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
        );
      }
    }