触发 setState 函数在父级中从承诺.然后在子级



我正在尝试从childpromise内的parent中找到setState的解决方案。

parentcomponent

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将从childcomponent触发

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

this.props.handleTransition希望通过then触发onSubmit

如果您需要更多详细信息,请告诉我?我宁愿不使用库或包来实现这一点,但如果它使生活更轻松,我可以考虑。Redux 可能是最好的选择,但除非必要,否则我宁愿不要这样做。

注意:this.props.handleTransition();完成了这项工作,但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
);
}
}

最新更新