简体   繁体   English

性能:在 React 中调度动作与作为道具传递

[英]Performance: Dispatching an action vs passing as props in React

I have a technical question.我有一个技术问题。 I am trying to pass a value from child component to store by using action dispatcher inside my child component.我试图通过在我的子组件中使用动作调度程序将一个值从子组件传递到存储。 This action dispatcher then updates the state value in the reducer.然后,此操作调度程序更新减速器中的 state 值。

Is it advisable to pass value from the child component this way?以这种方式从子组件传递值是否可取? will it affect the performance of the react app?它会影响反应应用程序的性能吗?

Or should I use props to pass from child to parent component and then update the state.或者我应该使用道具从子组件传递到父组件,然后更新 state。

Please advise as I searched a lot about this but didn't get any info.请告知,因为我对此进行了很多搜索,但没有得到任何信息。

Problem with passing dispatcher to your child is your child component is not very reusable.将调度程序传递给您的孩子的问题是您的孩子组件不是很可重用。 I would suggest to pass a callback method to your child which contains the logic of dispatching the event.我建议将回调方法传递给您的孩子,其中包含调度事件的逻辑。

Parent:家长:

class ParentComponent extends React.Component {

  loginHandler(){
    ...
    this.props.someMethod();
  }

  render() {
    return {
      ...
      <ChildComponent click="loginHandler"></ChildComponent>
      ...
    }
  }
}
const mapDispatchToProps = dispatch => {
  return {
    // dispatching plain actions
    ...
    someMethod: () => dispatch({ ... }),
    ...
  }
}
export default connect(null, mapDispatchToProps)(ParentComponent);

Child Component:子组件:

function ChildComponent({click}) {
  return {
    ...
    <button click={click}></button>
    ...
  }
}

Now with this approach your child approach doesn't carry any business logic.现在使用这种方法,您的子方法不带有任何业务逻辑。 It can be used at multiple places.它可以在多个地方使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM