gpt4 book ai didi

javascript - 如何先更新子状态然后更新父状态

转载 作者:行者123 更新时间:2023-12-01 01:15:15 24 4
gpt4 key购买 nike

In short :-

我想先更新子状态,然后更新父状态,但 react 批处理 setSate 并首先调用父 setState,然后调用子状态。为了获得更多理解,请阅读下面的解释。

Basically i have a parent component which is having two child.

  1. 排序组件:-此组件打开一个用于选择排序选项的下拉列表。单击时,它应该更新本地状态,然后调用从父级作为 props 传递的函数。
  2. 产品集合:-此组件根据所选排序显示产品。

我将一个函数 (handleClick) 从父组件传递给 sort,以将所选排序的值传递到父组件中,然后将其传递给产品集合。

由于排序是一个下拉列表,我想在用户选择一个选项后首先关闭它,然后更新父级。

现在我正在以这种方式使用它,首先更新本地状态并在回调中调用从父级传递的函数。

handleClick(param) {
this.setState({ selectedType: param.slug }, () =>
this.props.onHandleSort(param.slug)
)
}

但正如 React docs 中所写它对进程进行批处理,并首先调用父进程 setState,然后再调用子进程。

For example, that if both Parent and Child call setState during a click event, Child isn’t re-rendered twice. Instead, React “flushes” the state updates at the end of the browser event. This results in significant performance improvements in larger apps.

我需要它以这种方式发生只是因为我需要首先关闭我的下拉列表并且父级应该更新。

I have tried the following this but nothing seems to work.

  1. 使排序组件无状态并依赖于父级的 props,但这需要一些时间才能关闭下拉列表。
  2. 使用了 setState 的回调,但正如文档中所写,它首先批处理并调用父 setState,然后调用子 setState。

最佳答案

your codepen来看,您应该将 withRouter 包装器提升到父级,让它找出 selectedType 并将其传递给您的排序组件。然后,您可以在 onHandleSort 中设置新的查询

class Parent extends Component {
// ...
handleClick (slug) => {
this.props.router.push({ query: { sorting: slug } })
}
// ...
render () {
const sorting = this.props.router && this.props.router.query
? this.props.router.query.sorting
: 'RELEVANCE';

return (
// ...
<Sort value={sorting} onHandleSort={this.handleClick} />
// ...
);
}
}

export default withRouter(Parent);

export default class Sort extends Component {
// ...
handleClick (param) => {
this.props.onHandleSort(param.slug)
}
// ...
render () {
const selectedType = this.props.sorting;

return (
// ...
);
}
}

关于javascript - 如何先更新子状态然后更新父状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821856/

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