【问题标题】:Set state and run function on a single onClick event在单个 onClick 事件上设置状态和运行函数
【发布时间】:2017-05-16 21:23:05
【问题描述】:

我需要设置状态并在 onClick 事件上运行函数。我如何在 React 中实现这一点?

我试图将这两件事放在their own function 中,但这在下面给了我这个警告。

警告:setState(...):在现有状态转换期间无法更新(例如在render 或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移至componentWillMount

editLink(onEditLink, link) {
  this.setState({showContent: false});
  onEditLink(link);
}

render() {
  return (
    <a onClick={this.editLink(this.props.onEditLink, this.props.link)}>Edit</a>
  )
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    问题是您立即调用该函数,而不是分配将在单击元素时执行的新函数:

    editLink(onEditLink, link) {
      this.setState({showContent: false});
      onEditLink(link);
    }
    
    render() {
      return (
        <a onClick={() => this.editLink(this.props.onEditLink, this.props.link)}>Edit</a>
      )
    }
    

    您要做的是传递一个函数,该函数在执行时将使用这些参数调用您的 this.editLink 函数。

    【讨论】:

      【解决方案2】:

      setState 接受一个回调函数作为它的第二个参数,我建议你使用它:

      editLink(onEditLink, link) {
        this.setState({showContent: false}, () => {
           onEditLink(link);
        });
      }
      

      setState() 的第二个参数是一个可选的回调函数 将在 setState 完成并且组件为 重新渲染。通常我们建议使用 componentDidUpdate() 而是这样的逻辑。

      【讨论】:

      • 嗯,您的解决方案似乎很合理。但是尝试一下,我仍然收到该警告消息..
      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多