gpt4 book ai didi

javascript - React - 仅当调用 Parent 中的方法时,如何将 Child 中的方法调用到 setState?

转载 作者:行者123 更新时间:2023-11-30 14:49:27 25 4
gpt4 key购买 nike

我有一个父组件和 2 个子组件。每个 child 都是一个输入字段,第二个输入取决于第一个输入字段的选择。仅当 Parent 中的函数被执行时,是否有可能在 react 中调用函数 insight sibling 2?在我的例子中:Child1 提供 ID, parent 使用 ID,Child2 应该使用相同的 ID 发出 http 请求。

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

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)

};

最佳答案

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

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

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

关于javascript - React - 仅当调用 Parent 中的方法时,如何将 Child 中的方法调用到 setState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com