【问题标题】:Trigger a function when action is dispatched from other component从其他组件分派动作时触发函数
【发布时间】:2017-10-18 17:20:36
【问题描述】:

我正在开发一个 reactjs 应用程序并使用 redux。我有两个组件。说组件 A组件 B。在组件 A 中,我有一张桌子。当我单击任何行时,我将使用行的数据作为该操作的参数调度一个操作。每次单击一行时,都会调度此操作。每当单击一行并调度该操作时,我想触发组件 B 中的一个函数。我该怎么做?

通常我们通过 action dispatch 更改 reducer 中的数据,然后将这些数据用作其他组件中的状态。但是这里我想在组件 A 的表中单击一行时触发组件 B 中的一个函数。

【问题讨论】:

  • 组件 B 是组件 A 的父组件吗?
  • 没有。它们是分开的。

标签: javascript reactjs redux react-redux


【解决方案1】:

单击行时在 A 中调度一个操作,将布尔值设置为 true。然后使用 mapStateToProps 在 Redux 状态更改时重新渲染组件。然后在componentDidUpdate()内部对所需函数进行条件调用:

class B extends React.Component {
  componentDidUpdate() {
    const { rowClickedInAComponent } = this.props;
    if ( rowClickedInAComponent ) {
      functionToBeCalled();
    }
  }
  render() {
  }
}

const mapStateToProps = (state) => ({
  rowClickedInAComponent: rowClickedInAComponent
  // boolean here, you could pass any info such as which row was clicked
});

export default connect(mapStateToProps)(ListingPage);

如果您需要进一步说明,请发表评论。

【讨论】:

  • 是的。但是你可以传递任何值,正如我在评论中提到的那样
  • 因此,即使标志值从“true”变为“true”,每次都会执行 functionToBeCalled()。我的意思是每次单击该行时,都会执行 functionToBeCalled() 吗?
  • 不,因为你必须传递任何其他每次肯定会改变的值。我确定你会想要传递一些关于点击了哪一行的信息。
  • 看看这就是问题所在。如果减速器发生变化,那么我应该如何检查它?说行ID发生了变化。现在该怎么办?
  • 我的组件 B 也是视频播放器。所以当我播放播放器时,componentUpdate 会无限运行。有什么解决办法吗?
【解决方案2】:

您可以通过以下几种方式实现这一目标。

i) 如果存在 父子 关系,只需将 activeRow 函数作为子组件的 props 传递

  class ComponentA extends React.component{

  render(){
    return(
    {/*view, could be table, section, div, etc.*/}
      <div>
        <button onClick={this.props.handler}>Click me</button>
      </div>
    )
  }
}

class ComponentB extends React.component{

  handleClick(){
    //do something.
    console.log("clicked!");
  }
  
  render(){
    return(
    {/*view, could be table, section, div, etc.*/}
      <div>
        <ComponentA handler={this.handleClick}/>
      </div>
    )
  }
}

ii) 使用 redux,在 redux 状态下创建一个 activeRow 键,并使用 react-redux's connect 方法创建 subscribe componentB。
现在在componentB 添加componentWillReceiveProps 生命周期钩子,并在componentWillReceiveProps 里面做一些事情
例如:

componentWillReceiveProps(nextProps){
  //first parameter is updated props.
  //check this.props with nextProps.
  //do something here.
}

【讨论】:

  • 但是 this.state.activeRow.id 和 props.activeRow.id 都是一样的。正确的?您必须通过 this.state.activeRow.id = props.activeRow.id 来维护 this.state.activeRow.id。那么在任何时候,他们怎么会不相等呢?
  • 那么我们不明白你的逻辑:(如果行 ID 没有改变,你为什么要更新?
  • 行 ID 正在改变。但是一旦行 id 改变 this.state.activeRow.id 也会改变,对吧?因为我们必须做 setState({ this.state.activeRow.id: props.activeRow.id })
  • 看起来不错。但请使用props 键进行深度检查,而不仅仅是nextProps === this.props
  • 这是一个例子,你可以为所欲为
猜你喜欢
  • 1970-01-01
  • 2016-08-03
  • 2019-07-20
  • 2017-02-05
  • 1970-01-01
  • 2020-09-08
  • 2022-10-24
  • 2022-07-21
  • 2019-09-25
相关资源
最近更新 更多