【问题标题】:React - How to call method in Child to setState, ONLY when a method in Parent was called?React - 如何调用 Child 中的方法到 setState,仅当调用 Parent 中的方法时?
【发布时间】:2018-07-02 09:58:01
【问题描述】:

我有一个父组件和 2 个子组件。每个孩子都是一个输入字段,第二个输入取决于第一个输入字段的选择。是否可以响应调用函数洞察兄弟 2,仅当执行 Parent 中的函数时?在我的情况下:Child1 提供 ID,父母使用 ID,Child2 应该使用相同的 ID 发出 http 请求。

在我的代码下面(我遗漏了很多只是为了没有太多(不必要的代码),所以如果我遗漏了什么请告诉我)在 Parent 内部,“updateId”方法从 child1 接收了它的参数,只有当这种情况发生时(提供了 id),我才想在 Sibling 中调用“getData”方法。我在想我可以在 Parent 设置为 true 时创建布尔值,当给定 id 时,将它传递给 Sibling,只有在它为 true 时才调用“getData”方法,但据我所知,这在反应中是不可能的?!我怎么能这样做?

PS - 我有意在我的子组件中设置状态,因为我试图保持输入 (child=input) 独立,可以轻松交换。

export default class Parent extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            id: ""
        }
        this.updateId=this.updateId.bind(this);
    }

    updateId (id){
        this.setState({
            id:id
        })

    }

    render() {
        return (
            <div>
                <Child onChange={this.updateId} />
                <Sibling id={this.state.id}/>
            </div>
        )
    }
};

import apicall from :/....jsx;
export default class Sibling extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            siblings: []
        }
        this.getData=this.getData.bind(this);
    }

    getData (this.props.id){
        apiCall(this.props.id).then(response=> {
            this.setState({
                siblings:response
            })

    }

    render() {
        return ...
    }
};

    export default class Child extends React.Component {
    ...
    get ID
    ...
    call this.props.onChange(selected.value)

    };

【问题讨论】:

  • 您可以将子组件的状态提升到父组件,并让父组件向子组件提供必要的信息。我认为这个答案可能会对您有所帮助stackoverflow.com/questions/46594900/…
  • 是的,但重点是我试图不这样做 - 我希望每个输入(子组件)的选项都在该部分的状态内。孩子
  • 那么您可以做的其他事情是您可以访问父级中的子引用并使用来自父级的引用执行函数,例如stackoverflow.com/questions/40235420/…
  • 我最终做的是使用 componentWillReceiveProps,所以我在 child 中的方法将在收到道具后立即被调用,并且工作正常。

标签: javascript reactjs


【解决方案1】:

在这种情况下,我通常会在父组件(或像 Redux 这样的系统)中保持状态,并让子组件保持简单和愚蠢。因此,我会在父级中执行 API 工作,并将生成的数据传递给子级。

也就是说,您的 Sibling 组件可以挂接到 componentWillReceiveProps 并在 ID 属性发生变化时更新其状态。

https://reactjs.org/docs/react-component.html#componentwillreceiveprops

【讨论】:

    【解决方案2】:

    为了避免孩子与孩子之间的沟通混淆使用Redux,它可以帮助你实现你想要的功能。它还可以帮助您制作哑组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      相关资源
      最近更新 更多